Adding DataRow into a New Datatable error saying the row is already associated to a table

67 Views Asked by At

I am using the below code in Visual Studios to go through each DataRow in a table and include an If statement to say where if a certain criteria is met, it creates a DataRow. I then want that DataRow to then be added into dt_tempHold for use later on in my program. Is "dt_tempHold.Rows.Add(dr_EPA);" not the thing to use here because I get an error saying that the row already belongs to another table? I just want a copy of the DataRow, into the DataTable as it goes through the ForEach and the If statements.

        DataTable dt_tempHold = new DataTable();

        foreach (DataRow dr in ds_picsData.Tables["Placemnt"].Rows)
        {
            if (ds_spreadsheetdata.Tables["EPABase"].AsEnumerable().Any(t => t.Field<string>("EPA_ORG_ID") == dr["NAME"].ToString()))
            {

                DataRow dr_EPA = ds_spreadsheetdata.Tables["EPABase"].AsEnumerable().FirstOrDefault(t => t.Field<string>("EPA_ORG_ID") == dr["NAME"].ToString());

                dt_tempHold.Rows.Add(dr_EPA);

                dr["ADDR1"] = dr_EPA["Contact_address1"].ToString();
                dr["ADDR2"] = dr_EPA["Contact_address2"].ToString();
                dr["ADDR3"] = dr_EPA["Contact_address3"].ToString();
                dr["ADDR4"] = dr_EPA["Contact_address4"].ToString();
                dr["POSTCODE"] = dr_EPA["Postcode"].ToString();
                dr["PHONE"] = dr_EPA["Contact_number"].ToString();
                dr["EMAIL"] = dr_EPA["Contact_email"].ToString();
                dr["NAME"] = dr_EPA["EP_Assessment_Organisations"].ToString();



            }

        };
0

There are 0 best solutions below