-->

CheckBox inside GridView and handle its events to get records based on its Checked state.


Introduction

In this post, I explain how to use checkbox inside gridview and how to handle its events to get records based on its checked state.

When we get tabular data from the database and want to show on the UI, We can use Gridview Control. But Sometimes it's required to process some selected records only or sometimes all records. To do this we need to use checkbox inside gridview But if Gridview contains huge data like 100, 200,  then select all record is very time-consuming. We can do this very easily using javascript with providing to select all option.

Steps :

Just follow the steps and get result easily.

Step-1 : Create New Project

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table and insert data for shown in Gridview.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add Web Page.

Go to Solution Explorer > Right Click on Project under solution explorer > Add > New item > Select Web Form using Master Page under web > Enter Name > > Select Master Page>Add.
(Complete Code in Source Code)

Here is HTML Code for Gridview

<asp:GridView ID="GridView1"  Width="500px" runat="server" AutoGenerateColumns="False" DataKeyNames="StudentID" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal">
    <Columns>
        <asp:TemplateField >
            <HeaderTemplate>                   
                    &nbsp;&nbsp; <asp:CheckBox ID="chkCheckAll" runat="server" onclick="javascript:SelectAllCheckboxes(this)" />
            </HeaderTemplate>
            <ItemTemplate>
                &nbsp;&nbsp;<asp:CheckBox ID="chkCheck" runat="server" onclick="javascript:CheckedCheckboxes(this)" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Student Name">
            <ItemTemplate>
                <asp:Label ID="lblStudentName" runat="server" Text='<%#Eval("StudentName") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField  HeaderText="Class">
            <ItemTemplate>
                <asp:Label ID="lblClass" runat="server" Text='<%#Eval("Class") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField  HeaderText="Class">
            <ItemTemplate>
                <asp:Label ID="lblRollNo" runat="server" Text='<%#Eval("RollNo") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
    <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
    <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#F7F7F7" />
    <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
    <SortedDescendingCellStyle BackColor="#E5E5E5" />
    <SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>

Step-6: Add Code For Populate Data.

Write the followings code in your page load event for fetch Data from Database and show in gridview.

PAGE LOAD CODE
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        populateData();
    }
}

And Here is the function code
private void populateData()
{
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        GridView1.DataSource = dc.StudentMasters.ToList();
        GridView1.DataBind();
    }
}

Step-7: Add Javascript code for Select Gridview Record(s).

<script src="Scripts/jquery-1.7.1.js"></script>
<script language="javascript" type="text/javascript">
    function SelectAllCheckboxes(chk) {
        var totalRows = $("#<%=GridView1.ClientID %> tr").length;
        var selected = 0;
        $('#<%=GridView1.ClientID %>').find("input:checkbox").each(function () {
            if (this != chk) {
                this.checked = chk.checked;
                selected += 1;
            }
        });
    }

    function CheckedCheckboxes(chk) {
        if (chk.checked) {
            var totalRows = $('#<%=GridView1.ClientID %> :checkbox').length;
            var checked = $('#<%=GridView1.ClientID %> :checkbox:checked').length
            if (checked == (totalRows - 1)) {
                $('#<%=GridView1.ClientID %>').find("input:checkbox").each(function () {
                    this.checked = true;
                });
            }
            else {
                $('#<%=GridView1.ClientID %>').find('input:checkbox:first').removeAttr('checked');
            }
        }
        else {
            $('#<%=GridView1.ClientID %>').find('input:checkbox:first').removeAttr('checked');
        }
    }       
</script>

Step-8: Write following code in Button Click Event to get Selected records.  

protected void Button1_Click(object sender, EventArgs e)
{
    string Selected = "";
    foreach (GridViewRow gr in GridView1.Rows)
    {
        CheckBox cb = (CheckBox)gr.FindControl("chkCheck");
        Label lblName = (Label)gr.FindControl("lblStudentName");
        // You can get other value same way               

        if (cb != null && cb.Checked)
        {
            string StdID = GridView1.DataKeys[gr.DataItemIndex].Values["StudentID"].ToString();
            Selected += "Student ID : " + StdID + ", Name : " + lblName.Text.Trim() + "<br/>";
        }
    }

    lblResult.Text = Selected;
}

STEP-9: Run Application

Run Application and Get result in your browser.
Thank You

Download Source Code

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.