Wednesday, 8 August 2012

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 toaccommodate 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 ds = new DataSet();
        DataSet dsCopy = new DataSet();
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                dsCopy.Tables[0].ImportRow(dr);
            }
        }

No comments:

Post a Comment

What should you required to learn machine learning

  To learn machine learning, you will need to acquire a combination of technical skills and domain knowledge. Here are some of the things yo...