Hello All, We are going to start new batch from next week. message/call or mail us for more details.

5 July 2012

Using JavaScript with ASP.Net GridView Control

Abstract: Here I am going to explained how to use JavaScript with ASP.Net GridView Control and implementing functionalities such as check all checkboxes and highlighting a row. 




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.

<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

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)"); 
    }
}

Find Complete Code Below....

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="CSharp.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Scrollable Grid</title>
    <style type ="text/css" >
        .header
        {
           background-color:Green;
        }
    </style> 
<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>
<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>
<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>   
</head>
<body>
    <form id="form1" runat="server">
    <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="EMPLOYEE_ID" HeaderText="Employee Id"  />
    <asp:BoundField ItemStyle-Width="150px" DataField="FIRST_NAME" HeaderText="First Name" />
    <asp:BoundField ItemStyle-Width="150px" DataField="LAST_NAME" HeaderText="Last Name"/>
    <asp:BoundField ItemStyle-Width="150px" DataField="EMPLOYEE_CODE"  HeaderText= "Employee Code"/>
    </Columns> 
    </asp:GridView>
    </form>
</body>
</html>



CS Page
protected void Page_Load(object sender, EventArgs e)
    {
        string strQuery = "select top 10 * from employee";
        SqlCommand cmd = new SqlCommand(strQuery);
        DataTable dt = GetData(cmd);
        GridView1.DataSource = dt;
        GridView1.DataBind();
       
    }
    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)");  
        }
    }
    private DataTable GetData(SqlCommand cmd)
    {
        DataTable dt = new DataTable();
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        SqlDataAdapter sda = new SqlDataAdapter();
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            return dt;
        }
        catch (Exception ex)
        {
            //Response.Write(ex.Message);
            //return null;
            throw ex;
        }
        finally
        {
            con.Close();
            sda.Dispose();
            con.Dispose();
        }
    }