How to Copy Rows From One DataSet to Another DataSet in ASP.NET using C#


Copy Rows From One DataSet to Another DataSet in ASP.NET using C#. DataSets in ASP.NET are usually read-only.  This means that it is difficult to copy a row from one DataSet to another. Using the following code you can easily filter rows from one DataSet to another.

Example:
//Here I am using emprecord table to fill the first data set

        SqlConnection Mycon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].
ToString());
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "select * from emprecord";
        cmd.Connection = Mycon;
        DataSet ds = new DataSet();
        SqlDataAdapter MyAd = new SqlDataAdapter(cmd);
        //Now we will use SqlDataAdapter fill() method to fill data in dataset table.
         MyAd.Fill(ds);
        // Now here ds contains data in it now we have to copy this data to another Dataset for this use below code.

         DataSet ds1 = new DataSet();

        //this line will only copy the structure of DataSet ds to DataSet ds1
         ds1 = ds.Clone();

         for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
         {
             //here you can filter your rows according to your choice.
             if (ds.Tables[0].Rows[i].ItemArray[1].ToString() != "Shanti Trivedi")
             {
                 ds1.Tables[0].ImportRow(ds.Tables[0].Rows[i]);
             }
         }

The below image shows the rows in both dataset.

Real Data (rows in ds)

EmpId
EmpName
Location
Phone
1
Rajesh Trivedi
Raibareli
9795507829
2
Rajkumar
Kanpur
3456789876
3
Shanti Trivedi
New Delhi
1234567654
4
visnu
New Delhi
5656565655665
5
susil
New Delhi
545435345345

Filterd Data(Rows in ds1)

EmpId
EmpName
Location
Phone
3
Shanti Trivedi
New Delhi
1234567654
4
visnu
New Delhi
5656565655665
5
susil
New Delhi
545435345345

Tags: , ,

Join Us!