Comparing Two columns values in database

In this blog we will know how to Compare Two columns values in database and show the output in a Gridview.

 

Table creation

Create two tables named as t1 and t2 having id column each on both the tables.

Table t1                Table t2

id                         id

1                           3

2                           4

3                           5

4                           6

 

Default.aspx code

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <asp:GridView ID="GridView1" runat="server" ForeColor="#FF3300">

    </asp:GridView>

    <asp:Button ID="btnc_1to2" runat="server"

        Text="compare column1's values with column2" onclick="btnc_1to2_Click"

            Width="250px" /><br />

   

    <asp:GridView ID="GridView2" runat="server" ForeColor="#663300">

    </asp:GridView>

    <asp:Button ID="btnc_2to1" runat="server"

        Text="compare column2's values with column1" onclick="btnc_2to1_Click"

            Width="250px" />

    </div>

    </form>

</body>

</html>

 

 

Default.aspx.cs code

 

using System;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page

{

    string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

    string str;

    SqlCommand com;

   

    protected void btnc_1to2_Click(object sender, EventArgs e)

    {

        SqlConnection con = new SqlConnection(strConnString);

        con.Open();

        str = "select * from t1 except select * from t2";

        com = new SqlCommand(str, con);

        SqlDataReader reader = com.ExecuteReader();

        GridView1.DataSource = reader;

        GridView1.DataBind();

        con.Close();

    }

    protected void btnc_2to1_Click(object sender, EventArgs e)

    {

        SqlConnection con = new SqlConnection(strConnString);

        con.Open();

        str = "select * from t2 except select * from t1";

        com = new SqlCommand(str, con);

        SqlDataReader reader = com.ExecuteReader();

        GridView2.DataSource = reader;

        GridView2.DataBind();

        con.Close();

    }

}

 

Output

Thanks for reading

Ebook Download
View all
Learn
View all