Skip to main content

Implement check all checkbox functionality in ASP.Net GridView control using JavaScript


In this Article, I am explaining how to make use JavaScript in the ASP.Net GridView control and make it more elegant by reducing postbacks.
Functions such as
1.     Highlighting selected row
2.     Check/Uncheck all records using single checkbox.
3.     Highlight row on mouseover event.
The above three functions can be easily achieved using JavaScript thus avoiding postbacks.

Basic Concept

The basic concept behind this is when the GridView is rendered on the client machine it is rendered as a simple HTML table. Hence what the JavaScript will see a HTML table and not the ASP.Net GridView control.
Hence once can easily write scripts for GridView, DataGrid and other controls once you know how they are rendered.

To start with I have a GridView control with a header checkbox and checkbox for each individual record

<asp:GridView ID="GridView1" runat="server"  HeaderStyle-CssClass = "header"
AutoGenerateColumns = "false" Font-Names = "Arial"
OnRowDataBound = "RowDataBound"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" >
<Columns>
<asp:TemplateField>
    <HeaderTemplate>
      <asp:CheckBox ID="checkAll" runat="server" onclick = "checkAll(this);" />
    </HeaderTemplate>
   <ItemTemplate>
     <asp:CheckBox ID="CheckBox1" runat="server" onclick = "Check_Click(this)" />
   </ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="CustomerID" HeaderText="CustomerID"  />
<asp:BoundField ItemStyle-Width="150px" DataField="City"
HeaderText="City" />
<asp:BoundField ItemStyle-Width="150px" DataField="Country"
HeaderText="Country"/>
<asp:BoundField ItemStyle-Width="150px" DataField="PostalCode"  HeaderText= "PostalCode"/>
</Columns>
</asp:GridView>

Above you will notice I am calling two JavaScript functions checkAll and Check_Click which I have explained later. Also I have attached a RowDataBound event to the GridView to add mouseover event
 

  
Highlight Row when checkbox is checked

<script type = "text/javascript">
function Check_Click(objRef)
{
    //Get the Row based on checkbox
    var row = objRef.parentNode.parentNode;
    if(objRef.checked)
    {
        //If checked change color to Aqua
        row.style.backgroundColor = "aqua";
    }
    else
    {   
        //If not checked change back to original color
        if(row.rowIndex % 2 == 0)
        {
           //Alternating Row Color
           row.style.backgroundColor = "#C2D69B";
        }
        else
        {
           row.style.backgroundColor = "white";
        }
    }
   
    //Get the reference of GridView
    var GridView = row.parentNode;
   
    //Get all input elements in Gridview
    var inputList = GridView.getElementsByTagName("input");
   
    for (var i=0;i<inputList.length;i++)
    {
        //The First element is the Header Checkbox
        var headerCheckBox = inputList[0];
       
        //Based on all or none checkboxes
        //are checked check/uncheck Header Checkbox
        var checked = true;
        if(inputList[i].type == "checkbox" && inputList[i] != headerCheckBox)
        {
            if(!inputList[i].checked)
            {
                checked = false;
                break;
            }
        }
    }
    headerCheckBox.checked = checked;
   
}
</script>

The above function is invoked when you check / uncheck a checkbox in GridView row
First part of the function highlights the row if the checkbox is checked else it changes the row to the original color if the checkbox is unchecked.
The Second part loops through all the checkboxes to find out whether at least one checkbox is unchecked or not.
If at least one checkbox is unchecked it will uncheck the Header checkbox else it will check it


Check all checkboxes functionality

<script type = "text/javascript">
function checkAll(objRef)
{
    var GridView = objRef.parentNode.parentNode.parentNode;
    var inputList = GridView.getElementsByTagName("input");
    for (var i=0;i<inputList.length;i++)
    {
        //Get the Cell To find out ColumnIndex
        var row = inputList[i].parentNode.parentNode;
        if(inputList[i].type == "checkbox"  && objRef != inputList[i])
        {
            if (objRef.checked)
            {
                //If the header checkbox is checked
                //check all checkboxes
                //and highlight all rows
                row.style.backgroundColor = "aqua";
                inputList[i].checked=true;
            }
            else
            {
                //If the header checkbox is checked
                //uncheck all checkboxes
                //and change rowcolor back to original
                if(row.rowIndex % 2 == 0)
                {
                   //Alternating Row Color
                   row.style.backgroundColor = "#C2D69B";
                }
                else
                {
                   row.style.backgroundColor = "white";
                }
                inputList[i].checked=false;
            }
        }
    }
}
</script> 

The above function is executed when you click the Header check all checkbox When the Header checkbox is checked it highlights all the rows and checks the checkboxes in all rows.
And when unchecked it restores back the original color of the row and unchecks the checkboxes.

Note:
The check all checkboxes checks all the checkboxes only for the current page of the GridView and not all.

Highlight GridView row on mouseover event

<script type = "text/javascript">
function MouseEvents(objRef, evt)
{
    var checkbox = objRef.getElementsByTagName("input")[0];
   if (evt.type == "mouseover")
   {
        objRef.style.backgroundColor = "orange";
   }
   else
   {
        if (checkbox.checked)
        {
            objRef.style.backgroundColor = "aqua";
        }
        else if(evt.type == "mouseout")
        {
            if(objRef.rowIndex % 2 == 0)
            {
               //Alternating Row Color
               objRef.style.backgroundColor = "#C2D69B";
            }
            else
            {
               objRef.style.backgroundColor = "white";
            }
        }
   }
}
</script>

The above JavaScript function accepts the reference of the GridView Row and the event which has triggered it.
Then based on the event type if event is mouseover it highlights the row by changing its color to orange else if the event is mouseout it changes the row’s color back to its original before the event occurred.
The above function is called on the mouseover and mouseout events of the GridView row. These events are attached to the GridView Row on the RowDataBound events refer the code below

      
C#
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow )
    {
        e.Row.Attributes.Add("onmouseover","MouseEvents(this, event)");
        e.Row.Attributes.Add("onmouseout""MouseEvents(this, event)"); 
    }
}

VB.Net
Protected Sub RowDataBound(ByVal sender As Object,
ByVal e As GridViewRowEventArgs)
  If e.Row.RowType = DataControlRowType.DataRow Then
     e.Row.Attributes.Add("onmouseover""MouseEvents(this, event)")
     e.Row.Attributes.Add("onmouseout""MouseEvents(this, event)")
  End If
End Sub


You can try out the functionality discussed above using the sample GridView here


CustomerIDCityCountryPostalCode
ALFKIBerlinGermany12209
ANATRMéxico D.F.Mexico05021
ANTONMéxico D.F.Mexico05023
AROUTLondonUKWA1 1DP
BERGSLuleåSwedenS-958 22
BLAUSMannheimGermany68306
BLONPStrasbourgFrance67000
BOLIDMadridSpain28023
BONAPMarseilleFrance13008
BOTTMTsawassenCanadaT2F 8M4


The above JavaScript functions are tested in the following Browsers
1.     Internet Explorer 7
2.     Mozilla Firefox 3
3.     Google Chrome

You can download the source code here.


Comments

Popular posts from this blog

Editing Child GridView in Nested GridView

Editing Child GridView in Nested GridView In this article we will explore how to edit child gridview in the nested gridview.   Let''s write some code. Step 1:  Add scriptmanager in the aspx page. < asp : ScriptManager   ID ="ScriptManager1"   runat ="server"   EnablePageMethods ="true"> </ asp : ScriptManager > Step 2:  Add below stylesheet for modal popup. < style   type ="text/css">        .modalBackground        {              background-color : Gray;              filter : alpha(opacity=80);              opacity : 0.5;       }        .ModalWindow        {     ...

Hierarchical GridView in ASP.NET with AJAX, JQuery implementation - Part 1

Previously I had blogged some post related to showing two grids in hierarchical way. For example - when I need to show an invoice reports on the screen, the user requesting to show the list of invoices at initial time and they can drill down the details of item details of each invoice by clicking on respective row. The implementations can be in multiple ways, but I had blogged the implementation with AJAX and without AJAX using Java script on ASP.NET page. Below are the URLs of the same – Hierarchical GridView in ASP.NET Hierarchical GridView in ASP.NET with AJAX, Javascript implementation In this post I am taking the same requirements done before and enhance with some additional functionality as per readers expectations. The requirement on this implementation will be – The page should show a Grid View with list of Orders with Expand icon on the first column. On click of expand icon on each row, the Order Details of the Order must be fetched from the database ...

Scrollable Gridview With fixheader using JQuery in Asp.net

Scrollable Gridview With fixheader using JQuery in Asp.net Introduction: In this article I will explain how to implement scrollable gridview with fixed header in asp.net using JQuery.  Description:  In Previous posts I explained lot of articles regarding Gridview. Now I will explain how to implement scrollable gridview with fixed header in asp.net. I have one gridview that contains lot of records and I used  paging for gridview  but the requirement is to display all the records without paging. I removed paging at that time gridview occupied lot of space because it contains more records to solve this problem we implemented scrollbar.  After scrollbar implementation if we scroll the gridview we are unable to see Gridview header.   To implement Scrollable gridview with fixed header I tried to implement concept with css and JavaScript but there is no luck because maintaining fixed header working in IE but not in Mozilla and vice versa to ...