c# .net

How to check all rows in a gridview in asp.net?

How to check all rows in a gridview in asp.net?, someone asked me to explain?

In this article we will discuss how to check all rows in a gridview in asp.net using javascript. When user clicks on the header checkbox it call a javascript function on that we are written logic about checkall/uncheckall for a gridview.

 We will be using region table

Step 1: Create a table using the following script with data:

Click the button it will show a popup you can copy the SQL script data.

Step 2: Create a webform as gridview.aspx and copy and paste the following code. 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>check/uncheck all gridview in asp.net </title>
    <script type="text/javascript">
function UncheckHeader(headerchk) {
            var gvcheck = document.getElementById('gvdetails');
             var inputs = gvcheck.rows[0].getElementsByTagName('input');
                inputs[0].checked = false;
        function SelectAll(headerchk) {
            var gvcheck = document.getElementById('gvdetails');
            var i;
            //if true checked all checkboxes
            if (headerchk.checked) {
                for (i = 0; i < gvcheck.rows.length; i++) {
                   var inputs =gvcheck.rows[i].getElementsByTagName('input');
                   inputs[0].checked = true;
                //if condition fails uncheck allcheckboxes in gridview
            else {
                for (i = 0; i < gvcheck.rows.length; i++) {
                   var inputs =gvcheck.rows[i].getElementsByTagName('input');
                   inputs[0].checked = false;
    <form id="form1" runat="server">
        <asp:GridView ID="gvdetails" runat="server" >
                       <asp:CheckBox ID="chkheader" runat="server" onclick="javascript:SelectAll(this)" />
                        <asp:CheckBox ID="chkchild"  runat="server" onclick="javascript:UncheckHeader(this)" />

Step 3: In code behind gridview.aspx.cs, copy and paste the following code.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class gridview : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        List<string>result = new List<string>();
        using (SqlConnection con = new SqlConnection("Data Source=yourserver;IntegratedSecurity=true;Initial Catalog=Northwind;UserId=yourusername;Password=yourpassword"))
            DataSet ds = new DataSet();
            using (SqlCommand cmd = new SqlCommand("select * from Region", con))
                SqlDataAdapter da = new SqlDataAdapter(cmd);
            if (ds.Tables[0].Rows.Count > 0)
               gvdetails.DataSource = ds;


gridview checkall in asp.net

Post your comments / questions