Compare two DataTables and display matching records in C# .Net

Last Reply on Dec 12, 2014 08:44 AM By Azim

Posted on Dec 10, 2014 04:14 AM

Sir i want to compare the two tables using mysql database and display the matching data in repeater control

Posted on Dec 12, 2014 08:44 AM

Here i have used Dummy DataTable. You can use MySql table Data also.

Please refer this code.

HTML

<form id="form1" runat="server">
<div>
    GridView1
    <asp:GridView ID="GridView1" runat="server" />
    <br />
    GridView2
    <asp:GridView ID="GridView2" runat="server" />
    <br />
    GridView3
    <asp:GridView ID="GridView3" runat="server" />
</div>
</form>

Namespace

using System.Data;

C#

protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt1 = new DataTable();
    dt1.Columns.AddRange(new DataColumn[1] { new DataColumn("UserId") });
    dt1.Rows.Add("4");
    dt1.Rows.Add("11");
    dt1.Rows.Add("13");
    this.GridView1.DataSource = dt1;
    this.GridView1.DataBind();

    DataTable dt2 = new DataTable();
    dt2.Columns.AddRange(new DataColumn[2] { new DataColumn("UserId"), new DataColumn("Name") });

    dt2.Rows.Add("4", "John Hammond");
    dt2.Rows.Add("5", "Mudassar Khan");
    dt2.Rows.Add("6", "Suzanne Mathews");
    dt2.Rows.Add("13", "Robert Schidner");


    this.GridView2.DataSource = dt2;
    this.GridView2.DataBind();

    DataTable dt3 = dt2.Clone();
    foreach (DataRow row1 in dt1.Rows)
    {
        foreach (DataRow row2 in dt2.Rows)
        {
            if (row1["UserId"].ToString() == row2["UserId"].ToString())
            {
                dt3.ImportRow(row2);
            }
        }
    }

    this.GridView3.DataSource = dt3;
    this.GridView3.DataBind();
}

Screenshot