DataTable’s ImportRow & Clone methods [C#]

Discussion

Here, I will demonstrate the functionality of DataTable’s ImportRow & Clone methods and the difference between the Rows.Add & ImportRow.

Clone method will copy the structure of the existing table, only Columns and Schema, not the data. So in the following

DataTable dt = GetSomeVal();
DataTable dt1 = dt.Clone();
dt1 will have exactly the same Column type as of dt. However, dt1.Rows.Count will return 0.As for the other issue look at the following code::


DataTable dt1 = new DataTable();
DataRow dr1 = dt1.NewRow();
DataTable dt2 = new DataTable();

// will throw an error as dr1 already belongs to another datatable
dt2.Rows.Add(dr1); 

// will execute adding a new row to dt2 Table
dt2.ImportRow(dr1);

dt1.Rows.Add(dr1);

The above code is pretty much self-explanatory. If you have to add a DataRow from a different DataTable use ImportRow method otherwise use Rows.Add.

Happy Coding …

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s