OnCheckedChanged Event of CheckBox Control in ASP.Net

Introduction

This article explains the "OnCheckedChanged" event of the GridView control. The OnCheckedChanged event occurs when the checked state of the Checkbox control changes.

OnCheckedChanged Event

The OnCheckedChanged event handler of the ASP.Net Checkbox control allows us to handle the click event of a checkbox at the server side that is raised when the user clicks the checkbox control to changes it checked state. The "CheckedChanged" event occurs only if the "AutoPostBack" property of the checkbox control is "true".

<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" OnCheckedChanged="ChckedChanged" />

The OnCheckedChanged method also allows derived classes to handle the event without attaching a delegate

Now  I will show you how to use the OnCheckedChanged Event in a GridView. Use the following procedure to do that.

Create DataBase and Table in SQL Server

Create Database Employee

use Employee

create table EmployeeInformation

(

EmpId int,

Emp_Name varchar(max),

Emp_Address nvarchar(max),

Emp_Department varchar(max)

)

Write the following procedure to insert the values into table columns:

insert into EmployeeInformation values(101,'Pankaj Lohani','A-43 Vinod New Delhi','Web Development')

insert into EmployeeInformation values(102,'Nimit Joshi','B-44 Laxminagar New Delhi','Web Development')

insert into EmployeeInformation values(103,'Pravesh Khanduri','C-45 Pratap Vihar New Delhi','Teacher')

insert into EmployeeInformation values(104,'Amit Senwal','D-46 R.K puram New Delhi','Web Development')

insert into EmployeeInformation values(105,'Ravi Kumar','E-47 Saket New Delhi','Testing')

insert into EmployeeInformation values(106,'Ainul Hasan','F-48 Saraswati Kunj New Delhi','Web Development')

insert into EmployeeInformation values(107,'Ashish','F-49 Vinod Nagar New Delhi','Software Engineer')

 

Write the following query to execute the table schema:

 

select * from EmployeeInformation

 

 TalbeSchema

Step 1:

Open Visual Studio then select "Create New Website" --> "ASP.NET Web Site".

CreateNewWebsite

Step 2:

Now go to the Solution Explorer to the right side of the application and use the procedure shown in the following figure:

AddNewItem

Step 3:

Add a new Web form in the empty web application as shown in the following figure:

AddNewForm

Write the following code in a GridForm.aspx page :

Step 4:

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

 

<!DOCTYPE html>

 

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

<head runat="server">

    <title></title>

</head>

<body>

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

 <div>

<asp:GridView ID="gvEmpInfo" AutoGenerateColumns="False" CellPadding="4" runat="server" 

BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px">

<Columns>

<asp:TemplateField>

<ItemTemplate>

<asp:CheckBox ID="chkbox" runat="server" AutoPostBack="true" OnCheckedChanged="ChckedChanged" />

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField HeaderText="EmpId" DataField="EmpId" />

<asp:BoundField HeaderText="EmpName" DataField="Emp_Name" />

<asp:BoundField HeaderText="EmpAddress" DataField="Emp_Address" />

<asp:BoundField HeaderText="EmpDept" DataField="Emp_Department" />

</Columns>

       <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />

<HeaderStyle BackColor="#003399" Font-Bold="true" ForeColor="#CCCCFF" />

       <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />

       <RowStyle BackColor="White" ForeColor="#003399" />

       <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />

       <SortedAscendingCellStyle BackColor="#EDF6F6" />

       <SortedAscendingHeaderStyle BackColor="#0D4AC4" />

       <SortedDescendingCellStyle BackColor="#D6DFDF" />

       <SortedDescendingHeaderStyle BackColor="#002876" />

</asp:GridView>

<br />

<b>OnCheckedChanged Event Fired on Gridview</b>

<asp:GridView ID="gvMovedRows" AutoGenerateColumns="False" CellPadding="4" 

runat="server" ForeColor="#333333" GridLines="None">

    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />

<Columns>

<asp:BoundField HeaderText="EmpId" DataField="EmpId" />

<asp:BoundField HeaderText="EmpName" DataField="Emp_Name" />

<asp:BoundField HeaderText="EmpAddress" DataField="Emp_Address" />

<asp:BoundField HeaderText="EmpDept" DataField="Emp_Department" />

</Columns>

    <EditRowStyle BackColor="#999999" />

    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

<HeaderStyle BackColor="#5D7B9D" Font-Bold="true" ForeColor="White" />

    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />

    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />

    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />

    <SortedAscendingCellStyle BackColor="#E9E7E2" />

    <SortedAscendingHeaderStyle BackColor="#506C8C" />

    <SortedDescendingCellStyle BackColor="#FFFDF8" />

    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />

</asp:GridView>

  </div>

  </form>

</body>

</html>

 

Design View of GridForm.aspx

 

DesignView

 

Now write the following code in "GridForm.aspx.cs":

 

Step 4 :

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data;

using System.Data.SqlClient;

using System.Web.UI;

using System.Web.UI.WebControls;

 

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

{

    SqlConnection con;

    SqlDataAdapter adap;

    DataTable dt;

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            BindGridview();

        }

    }

    public GridForm()

    {

        con = new SqlConnection(@"Data Source=.;Initial Catalog=Employee;User ID=;Password=");

    }

    protected void BindGridview()

    {

        adap = new SqlDataAdapter("select * from EmployeeInformation", con);

        dt = new DataTable();

        adap.Fill(dt);

        gvEmpInfo.DataSource = dt;

        gvEmpInfo.DataBind();

    }

 

    protected void ChckedChanged(object sender, EventArgs e)

    {

        GetSelectedRows();

        BindSecondGrid();

    }

 

    protected void BindSecondGrid()

{

DataTable dt = (DataTable)ViewState["EmpDetails"];

gvMovedRows.DataSource = dt;

gvMovedRows.DataBind();

}

private void GetSelectedRows()

{

DataTable dt;

if (ViewState["EmpDetails"] != null)

    dt = (DataTable)ViewState["EmpDetails"];

else

dt = CreateTable();

for (int i = 0; i < gvEmpInfo.Rows.Count; i++)

{

    CheckBox chk = (CheckBox)gvEmpInfo.Rows[i].Cells[0].FindControl("chkbox");

if (chk.Checked)

{

    dt = MoveRows(gvEmpInfo.Rows[i], dt);

}

else

{

    dt = RemoveRow(gvEmpInfo.Rows[i], dt);

}

}

ViewState["EmpDetails"] = dt;

}

private DataTable CreateTable()

{

    DataTable dt = new DataTable();

    dt.Columns.Add("EmpId");

    dt.Columns.Add("Emp_Name");

    dt.Columns.Add("Emp_Address");

    dt.Columns.Add("Emp_Department");

    dt.AcceptChanges();

    return dt;

}

private DataTable MoveRows(GridViewRow gvRow, DataTable dt)

{

    DataRow[] dr = dt.Select("EmpId = '" + gvRow.Cells[1].Text + "'");

    if (dr.Length <= 0)

    {

        dt.Rows.Add();

        int rowscount = dt.Rows.Count - 1;

        dt.Rows[rowscount]["EmpId"] = gvRow.Cells[1].Text;

        dt.Rows[rowscount]["Emp_Name"] = gvRow.Cells[2].Text;

        dt.Rows[rowscount]["Emp_Address"] = gvRow.Cells[3].Text;

        dt.Rows[rowscount]["Emp_Department"] = gvRow.Cells[4].Text;

        dt.AcceptChanges();

    }

    return dt;

}

private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)

{

    DataRow[] dr = dt.Select("EmpId = '" + gvRow.Cells[1].Text + "'");

    if (dr.Length > 0)

    {

        dt.Rows.Remove(dr[0]);

        dt.AcceptChanges();

    }

    return dt;

}

}

 

Step 5 :

Debug the application by pressing F5 to execute the Web form. After debugging the application the output will be as in the following figure:

AfterDebug

Step 6 :

Now check the rows to move to another GirdView as shown in the following figure:

MoveRows

Step 7 :

If you will uncheck the rows then the moved rows will disappear from the GridView as shown in the following figure:

RemoveRows

Summary

The OnChckedChanged event occurs when the checked state of the checkbox control changes and it submits the web form to the server if the AutoPostBack property is true.