Web Development & Execution
David Addison
by David Addison
share this
« Back to the Blog

How to copy rows from one dataset to another in ASP.NET C#

How to copy rows from one dataset to another in ASP.NET C#

DataSets in ASP.NET are usually read-only. Data has an affinity with its parent DataSet. This means that it is difficult to copy a row from one DataSet to another. The source of your data should normally be altered to accommodate copying data. This is not always feasible though. In my situation, I needed to filter specific products from the originating DataSet. Unfortunately, I enountered many errors such as: "This row already belongs to another table".

Using the following code you can easily filter rows from one DataSet to another. I have bolded the areas you should pay attention to. ds1.Clone() replicates ONLY the structure of the DataSet. This is important if you were to just create a new DataTable and try to add new rows. ASP.NET would produce an error stating that the DataSet does not contain the same number of rows as the source. My first reaction was to use ds1.Tables[0].Rows.Add(), however, this did not work because of an error (e.g. the row already belongs to another DataSet).


DataSet ds1 = [Your Data Source] DataSet ds2 = new DataSet();

ds2 = ds1.Clone();

for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
if (ds1.Tables[0].Rows[i].ItemArray[0].ToString() != "SomeValue")
ds1 = ds2;


That's it. You should now be able to easily filter your dataset! As mentioned earlier, it would be more desirable to fix the source of your data. Filtering like this creates unnecessary overhead.


Thank you for contacting us!

We'll be in touch!

Back Home ×