Thursday, November 15, 2012

How to join two DataTables


How to join two DataTables using C#



I have found out the way to get the join of the tables using the GetParentRow() method in combination with a "Relation" in the DataSet.

Here is the code:

DataTable dt1 = new DataTable("Table1");
DataTable dt2 = new DataTable("Table2");
DataSet ds = new DataSet("DataSet");

dt1.Columns.Add("Eno"typeof(Int32));
dt1.Columns.Add("Ename"typeof(String));
dt1.Columns.Add("Salary"typeof(Double));
dt1.Columns.Add("Deptno"typeof(Int32));
dt1.PrimaryKey = new DataColumn[] { dt1.Columns["Eno"] };

dt2.Columns.Add("Deptno"typeof(Int32));
dt2.Columns.Add("Dname"typeof(String));
dt2.PrimaryKey = new DataColumn[] { dt2.Columns["Deptno"] };

ds.Tables.Add(dt1);
ds.Tables.Add(dt2);

// Loading data into dt1, dt2:
object[] o1 ={ 1, "dvs.kiran kumar", 50000.50, 10 };
object[] o2 ={ 2, "Raj", 4000.50, 20 };
object[] o3 ={ 3, "Gary", 10000.50, 10 };

object[] c1 ={ 10, "MFG" };
object[] c2 ={ 20, "EAS" };
object[] c3 ={ 30, "E&U" };
object[] c4 ={ 40, "PES" };

dt2.Rows.Add(c1);
dt2.Rows.Add(c2);
dt2.Rows.Add(c3);
dt2.Rows.Add(c4);

dt1.Rows.Add(o1);
dt1.Rows.Add(o2);
dt1.Rows.Add(o3);

DataRelation drel = new DataRelation("EquiJoin", dt2.Columns["Deptno"], dt1.Columns["Deptno"]);
ds.Relations.Add(drel);

DataTable jt = new DataTable("Joinedtable");
jt.Columns.Add("Eno"typeof(Int32));
jt.Columns.Add("Ename"typeof(String));
jt.Columns.Add("Salary"typeof(Double));
jt.Columns.Add("Deptno"typeof(Int32));
jt.Columns.Add("Dname"typeof(String));
ds.Tables.Add(jt);
foreach (DataRow dr in ds.Tables["Table1"].Rows)
{
       DataRow parent = dr.GetParentRow("EquiJoin");
       DataRow current = jt.NewRow();
       // Just add all the columns' data in "dr" to the New table.
       for (int i = 0; i < ds.Tables["Table1"].Columns.Count; i++)
       {
             current[ i ] = dr[ i ];
       }
       // Add the column that is not present in the child, which is present in the parent.
       current["Dname"] = parent["Dname"];
       jt.Rows.Add(current);
}
dataGridView1.DataSource = ds.Tables["Joinedtable"];

No comments:

Post a Comment