Joining Two DataTables into Single DataTable


Here I am going to explaing how to joing two datatables into a single DataTable.

Now I have a method which accepts two DataTables and returns a single DataTable which contains the Data of both the datatable.
Note:Structure of the both datatable must be same.


Private DataTable JoinDataTable(DataTable dt1,DataTable dt2)
{
DataTable dt = new DataTable();
DataRow dr;
dt = dt1.clone();// or you can clone the dt2 also like dt = dt2.clone();
for (int i=0;i{
dr = dt.NewRow();
for(int col1=0;dt1.Columns.Count;col1++)
{
dr[col1] = dt1.Rows[i][col1];
}
dt.Rows.Add(dr);
}
//Similarly Add the second DataTable
for (int j=0;j{
dr = dt.NewRow();
for(int col2=0;dt2.Columns.Count;col2++)
{
dr[col2] = dt2.Rows[j][col2];
}
dt.Rows.Add(dr);
}


return dt;
}


Comments

Author: asdfg15 Mar 2010 Member Level: Gold   Points : 1

if both the structures are same means then we can use SELECT statement like
"select name,num from table1,table2" .....
where name belongs to table1,num belongs to table2

Author: Dharmendra Kumar15 Mar 2010 Member Level: Gold   Points : 0

thats also a good way

Author: amjad17 Jun 2010 Member Level: Silver   Points : 0

nice way 2 add tables



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: