Friday, 25 May 2012

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.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.