Sunday, 9 July 2017

Check/uncheck or select/deselect all CheckBoxes using JavaScript in ASP.NET GridView

In this article, I am going to explain you, how to check and uncheck all checkboxes in asp.net gridview. If header row checkbox is checked then all row checboxes should be checked and if any of row checkbox is unchecked then header checkbox should be unchecked.

DOWNLOAD SOURCE CODE
check uncheck or select deselect all checkboxes using javascript
check uncheck or selectde select all checkboxes using javascript in gridview

Design GridView

In aspx file, create a gridview control as shown below and its contains 4 columns. First column contains header and row checkboxes. We are calling javascript funcion on click of header and row checkboxes.

<div align="center" style="margin-top: 30px;">
    <asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="false" Width="600px"
        AllowPaging="true" PageSize="5" OnPageIndexChanging="gvStudent_PageIndexChanging" CssClass="Grid"
        AlternatingRowStyle-CssClass="alt"
        PagerStyle-CssClass="pgr">
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox ID="chkHead" runat="server" onclick="chkHeadClick(this);">
                    </asp:CheckBox>
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="chkRow" runat="server" onclick="chkRowClick(this);" Style="text-align: center;">
                    </asp:CheckBox>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Student Id">
                <ItemTemplate>
                    <asp:Label ID="lblStudentId" runat="server" Text='<%#Eval("Id") %>'>
                    </asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Student Name">
                <ItemTemplate>
                    <asp:Label ID="lblStudentName" runat="server" Text='<%#Eval("Name") %>'>
                    </asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Student Subject">
                <ItemTemplate>
                    <asp:Label ID="lblStudentSubject" runat="server" Text='<%#Eval("Subject") %>'>
                    </asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Code-Behind File

In code-behind file, bind gridview control using dummy data as shown below.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
  public partial class WebForm1 : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if(!IsPostBack)
      {
          LoadStudentGrid();
      }
    }
    private void LoadStudentGrid()
    {
      //Creating DataTable of Student
      DataTable dt = new DataTable();
      //adding Columns to DataTable
      dt.Columns.Add("Id", typeof(Int32));
      dt.Columns.Add("Name", typeof(string));
      dt.Columns.Add("Subject", typeof(string));
      //adding Rows to DataTable
      dt.Rows.Add(1, "Rahul", "Maths");
      dt.Rows.Add(2, "Sachin", "Physics");
      dt.Rows.Add(3, "Yogesh", "Chemistry");
      dt.Rows.Add(2, "Sharad", "Economics");
      dt.Rows.Add(4, "Deepak", "Chemistry");
      dt.Rows.Add(5, "Savio", "Economics");
      dt.Rows.Add(6, "Sumit", "Physics");
      dt.Rows.Add(7, "Ram", "Chemistry");
      gvStudent.DataSource = dt;
      gvStudent.DataBind();
    }
    protected void gvStudent_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
      gvStudent.PageIndex = e.NewPageIndex;
      LoadStudentGrid();
    }
  }
}

JavaScript and CSS Code

Below is javascript and css file code. Write it in head tag.

<script type="text/javascript">

    // on header checkbox click 
    function chkHeadClick(checkbox) {
        // find out gridview
        var grid = document.getElementById("gvStudent");

        for (var i = 1; i < grid.rows.length; i++) {
            // iterating from row checkbox and set checked to true
            var inputs = grid.rows[i].cells[0].getElementsByTagName("INPUT");
            for (var j = 0; j < inputs.length; j++) {
                // check if inputs is of type checkbox
                if (inputs[j].getAttribute('type') == 'checkbox') {
                    grid.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = checkbox.checked;
                }
            }

        }

    }

    // on row checkbox click
    function chkRowClick(checkbox) {

        // find out gridview
        var grid = document.getElementById("gvStudent");

        var rowUncheckFlag = false;

        // count total number of row including header row, item row and pager row
        for (var i = 1; i < grid.rows.length; i++) {

            // start from item row [i=1] excluding header row[i=0] checkbox
            var inputs = grid.rows[i].cells[0].getElementsByTagName("INPUT");

            for (var j = 0; j < inputs.length; j++) {
                // check if inputs is of type checkbox
                if (inputs[j].getAttribute('type') == 'checkbox') {

                    if (grid.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked == false) {
                        rowUncheckFlag = true; // if any of row checkbox is unchecked then set rowUncheckFlag to true
                        break;
                    }
                }
            }
        }

        if (rowUncheckFlag) // if any checkbox is unchecked then make header check box unchecked
        {
            // here rows[0] means first row i.e header check box
            grid.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = false;
        }
        else {
            grid.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = true;
        }
    }
</script>

You can download background image files from Here.

<style type="text/css">
    .Grid {
        background-color: #fff;
        margin: 5px 0 10px 0;
        border: solid 1px #525252;
        border-collapse: collapse;
        font-family: Calibri;
        color: #474747;
    }
    .Grid td {
        padding: 2px;
        border: solid 1px #c1c1c1;
    }
    .Grid th {
        padding: 4px 2px;
        color: #fff;
        background: #363670 url(Images/grid-header.png) repeat-x top;
        border-left: solid 1px #525252;
        font-size: 0.9em;
    }
    .Grid .alt {
        background: #fcfcfc url(Images/grid-alt.png) repeat-x top;
    }
    .Grid .pgr {
        background: #363670 url(Images/grid-pgr.png) repeat-x top;
    }

    .Grid .pgr table {
        margin: 3px 0;
    }
    .Grid .pgr td {
        border-width: 0;
        padding: 0 6px;
        border-left: solid 1px #666;
        font-weight: bold;
        color: #fff;
        line-height: 12px;
    }
    .Grid .pgr a {
        color: Gray;
        text-decoration: none;
    }
    .Grid .pgr a:hover {
        color: #000;
        text-decoration: none;
    }
</style>
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON