Tuesday, September 2, 2008

Merging Two DataTables

private void MergeDataTable()

{

DataTable dtOne = new DataTable("MyFirstTable");

dtOne.Columns.Add("Number");

DataTable dtTwo = new DataTable("MySecondTable");

dtTwo.Columns.Add("Number");

// Populate the first table

for (int i = 1; i <= 10; i++)

{

DataRow row = dtOne.NewRow();

row["Number"] = "Data" + i;

dtOne.Rows.Add(row);

}

// Populate the second table

for (int i = 11; i <= 20; i++)

{

DataRow row = dtTwo.NewRow();

row["Number"] = "Data" + i;

dtTwo.Rows.Add(row);

}

// Now merge the two tables /* ONLY ONE LINE OF CODE COOL RIGHT! */

dtOne.Merge(dtTwo);

GridView1.DataSource = dtOne;

GridView1.DataBind();

}


Thanks,
Nitin Sharma
Software Programmer
.Net Technologies