CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
GridView with CheckBox – Select All and Highlight Selected Row

By Bala Murugan
Posted On Sep 17,2008
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 30
Category: ASP.Net 2.0/3.5
Print this article.

GridView with CheckBox – Select All and Highlight Selected Row

 

Introduction

To enable row selection in GridView, we can either include a Button control or CheckBox control. For example, selecting a row item to delete. Using CheckBox control will give a better user experience than a Button control and it is user friendly when we require multiple row selections. We can include checkbox in every row of GridView to enable selection of that particular row. To do this, we need to include a TemplateColumn that has a CheckBox control inside it. To enable “Select All” feature, we can include a checkbox inside the HeaderTemplate, which will give better experience than a Button control. Moving forward, this article will help us doing it from client side JavaScript Code.

 

When the user selects a CheckBox in a row, we can highlight the row by changing the row’s background color using JavaScript. Also, when the user clicks the checkbox in the header, we can select all the checkbox in the gridview. Refer the below figures.


Row Selection


Select All

 

Constructing GridView

Declare a GridView control with a TemplateColumn as the first column to include CheckBox control. Include BoundField for other fields to display in the GridView.

 

<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#010101" BorderStyle="Groove" BorderWidth="1px" CellPadding="4">

<Columns>

  <asp:TemplateField HeaderText="Roles">

     <HeaderTemplate>

         <asp:CheckBox ID="chkAll" onclick="javascript:SelectAllCheckboxesSpecific(this);" runat="server" />

     </HeaderTemplate>

      <ItemTemplate>

        <asp:CheckBox onclick="javascript:HighlightRow(this);" ID="chkDelete" runat="server" />

     </ItemTemplate>

   </asp:TemplateField>

 <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True" />

 <asp:BoundField DataField="FirstName" HeaderText="First Name" ReadOnly="True" />

 <asp:BoundField DataField="LastName" HeaderText="Last Name" ReadOnly="True" />

</Columns>

<FooterStyle BackColor="White" ForeColor="#330099" />

<RowStyle BackColor="White" ForeColor="#330099" />

<HeaderStyle BackColor="#F06300" Font-Bold="True" ForeColor="#FFFFCC" />

</asp:GridView>

 

To highlight the selected row, we will have JavaScript function called HighLightRow() and call this function on onclick event of the CheckBox in ItemTemplate.

Refer the below JavaScript function which does that.

function HighlightRow(chkB)

{

var IsChecked = chkB.checked;           

if(IsChecked)

  {

       chkB.parentElement.parentElement.style.backgroundColor='#228b22'; 

       chkB.parentElement.parentElement.style.color='white';

  }else

  {

       chkB.parentElement.parentElement.style.backgroundColor='white';

       chkB.parentElement.parentElement.style.color='black';

  }

}

 




Enabling Select All

If we see the rendered output of the GridView, it will be rendered as a HTML Table with ID as GridView ID.

Refer the below output.

 

<table cellspacing="0" cellpadding="4" rules="all" border="1" id="gvUsers" style="background-color:White;border-color:#010101;border-width:1px;border-style:Groove;border-collapse:collapse;">

              <tr style="color:#FFFFCC;background-color:#F06300;font-weight:bold;">

                     <th scope="col">

                            <input id="gvUsers_ctl01_chkAll" type="checkbox" name="gvUsers$ctl01$chkAll" onclick="javascript:SelectAllCheckboxesSpecific(this);" />

                        </th><th scope="col">Email</th><th scope="col">First Name</th><th scope="col">Last Name</th>

              </tr><tr style="color:#330099;background-color:White;">

                     <td>

                            <input id="gvUsers_ctl02_chkDelete" type="checkbox" name="gvUsers$ctl02$chkDelete" onclick="javascript:HighlightRow(this);" />

                        </td><td>test1@gmail.com</td><td>Babu</td><td>B</td>

//Goes on

 

So, we will first find the table from the rendered HTML and get all the checkbox inside table to check/uncheck depending on the state of the CheckBox control in header. Refer the below JavaScript function which selects all the checkbox inside the GridView when the Header CheckBox control is checked.

 

function SelectAllCheckboxesSpecific(spanChk)

       {

           var IsChecked = spanChk.checked;

           var Chk = spanChk;

              Parent = document.getElementById('gvUsers');          

              var items = Parent.getElementsByTagName('input');                         

              for(i=0;i<items.length;i++)

              {               

                  if(items[i].id != Chk && items[i].type=="checkbox")

                  {           

                      if(items[i].checked!= IsChecked)

                      {    

                          items[i].click();    

                      }

                  }

              }            

       }

 

Executing the page and see it in action.

Since, we are getting all the elements with tag name as “input”, the above code will check/uncheck the other CheckBox controls if present in any other column of the GridView control. To understand it better, include a checkbox at the last and execute the page. It will Check/Uncheck for the actions you do in the Header CheckBox. If you don’t have another checkbox control in the GridView, the above JavaScript code will work fine.

Refer the below figure.


 

To handle the above scenario with multiple CheckBox, we will change the code bit to check/uncheck the CheckBox control found based on the column location instead of checking all the CheckBox in the GridView. If we see the rendered HTML table, we have the checkbox at every first TD of the table. We will find the checkbox in every first TD and perform the required action. The below code does that.

 

function SelectAllCheckboxesMoreSpecific(spanChk)

       {

           var IsChecked = spanChk.checked;

           var Chk = spanChk;

              Parent = document.getElementById('gvUsers');                                                   

              for(i=0;i< Parent.rows.length;i++)

              {     

                  var tr = Parent.rows[i];

                 //var td = tr.childNodes[0];                                  

                  var td = tr.firstChild;         

                  var item =  td.firstChild;                     

                  if(item.id != Chk && item.type=="checkbox")

                  {           

                      if(item.checked!= IsChecked)

                      {    

                          item.click();    

                      }

                  }

              }            

       }

 

Configure the onclick event of header checkbox to point to the above JavaScript function.

The above code assumes the checkbox will be the first column of every row in the GridView. If the GridView have the selection CheckBox as the last column, then change the line which is bolded above to var item =  td.lastChild;

This code will work perfectly even if there are CheckBox controls present in any other column of the GridView control.

 

We can include a button that deletes the selected row,

 

protected void btnDelete_Click(object sender, EventArgs e)

    {

        for (int i = 0; i < gvUsers.Rows.Count;i++ )

        {

            CheckBox chbTemp = gvUsers.Rows[i].FindControl("chkDelete") as CheckBox;

            if (chbTemp.Checked)

            {

                Response.Write(gvUsers.Rows[i].Cells[1].Text + "<BR>");

                //Code for Deletion

 

            }

        }

    }

 

I took the example to delete the selected rows; it can be any operation that is specific to your requirement that can be done on the selected rows.

 

Download Source

Download Source 

Conclusion

Using CheckBox control to enable selection of a single row and selection of all the rows is a common task that we will do GridView control. This article will help you doing the same with JavaScript in client side. Download the source attached with this article.

Thanks for reading this article.

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Not Working Inside of Accordion
The code works beautifully when it is on a plane Web Form; however, when you toss the gridview into an Accordion, an error gets thrown on the line:

" var items = Parent.getElementsByTagName('input');"

Thoughts?
not delete
whene click on delete button ,sleected chekbox not cheked
ItemTemplate checkbox click then Not uncheck header checkbox
When I click on Header Checkbox then all Item check box checked it's perfect but when I click on Item checkbox then Header checkbox is not uncheck.
Check box Higlight
This script not working in mozila firefox

ie.
function HighlightRow(chkB)

{

var IsChecked = chkB.checked;

if(IsChecked)

{

chkB.parentElement.parentElement.style.backgroundColor='#228b22';

chkB.parentElement.parentElement.style.color='white';

}else

{

chkB.parentElement.parentElement.style.backgroundColor='white';

chkB.parentElement.parentElement.style.color='black';

}

}

Dynamically change grid view row color
check this site also for changing grid view color http://gridviewrowcolor.blogspot.com/
RE:no source code to download
Source code is available now. Thanks for letting us know!
no source code to download
there is no source code to down load... can u share it with us...
Superb
Great article, thanks for tip with Firefox. It works on Chrome as well.

Cheers.
GridView with CheckBox – Select All and Highlight Selected Row
Thanks for sharing this with the rest of us. I has been very useful to me. Regards, Steve B
Good
Very good article. Thanks a lot.
Can still be more clear.
Since we know that we need to check all checkbox in first cell of all rows, why can't we use Parent.rows[i].cells[0].children[0].checked = spanChk.checked

I think jQuery is good but then we are intentionally putting javascript code which are not optimized to show jQuery superior.....

just a thought.
Highlighting Issue in Firefox
The highlighting did not work for me in Firefox. The issue is with parentElement. Replace it with parentNode and works great! So the Javascript function will become as below:

function HighlightRow(chkB) {

var IsChecked = chkB.checked;
if (IsChecked) {
chkB.parentNode.parentNode.style.backgroundColor = '#FFE6A0';
chkB.parentNode.parentNode.style.color = '#003399';
} else {
chkB.parentNode.parentNode.style.backgroundColor = 'white';
chkB.parentNode.parentNode.style.color = 'black';
}
}
Good
Thank you very good
Ajax
This works well. The only problem I've had is that when it's in an update panel, any post back redraws the entire GridView which undoes the background color while leaving the checkbox checked.
Good
Thank you very good
thank you
excellent post
:)
Good practice
GridView with CheckBox – Select All and Highlight Selected Row
Following is the code which I used to get the required functionality.
However, when I click on the checkbox of any particular row, the row is not highlighting.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.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 runat="server">
<title>First Page</title>

<script language="javascript" type="text/javascript">

function SelectAllCheckboxes(spanChk)
{
var oItem = spanChk.children;
var theBox= (spanChk.type=="checkbox") ?
spanChk : spanChk.children.item[0];
xState=theBox.checked;
elm=theBox.form.elements;
for(i=0;i<elm.length;i++)
if(elm[i].type=="checkbox" &&
elm[i].id!=theBox.id)
{
if(elm[i].checked!=xState)
elm[i].click();
}
}
</script>
<script language="javascript" type="text/javascript">

function HighlightRow(chkB)
{



var IsChecked = chkB.checked;


if(IsChecked)
{

chkB.parentElement.parentElement.style.backgroundColor='Red';
chkB.parentElement.parentElement.style.color='Green';

document.getElementById(chkB).style.backgroundColor = "#ffffda";

}
else
{

chkB.parentElement.parentElement.style.backgroundColor='Black';
chkB.parentElement.parentElement.style.color='Orange';
}
}

</script>

</head>
<body>
<form id="form1" runat="server">

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="SNo"
DataSourceID="SqlDataSource1" Style="top: 135px; left: 302px; position: absolute;
height: 133px; width: 295px" >

<Columns>

<asp:TemplateField HeaderText="Select">

<HeaderTemplate>
<asp:CheckBox id="chkAll" onclick="javascript:SelectAllCheckboxes(this);" runat="server" />
</HeaderTemplate>

<ItemTemplate>
<asp:CheckBox onclick="javascript:HighlightRow(this);" ID="chkRow" runat="server" />
</ItemTemplate>

</asp:TemplateField>

<asp:BoundField DataField="SNo" HeaderText="SNo" InsertVisible="False" ReadOnly="True"
SortExpression="SNo" />
<asp:BoundField DataField="SName" HeaderText="SName" SortExpression="SName" />
<asp:BoundField DataField="PhoneNo" HeaderText="PhoneNo" SortExpression="PhoneNo" />
<asp:BoundField DataField="EMail" HeaderText="EMail" SortExpression="EMail" />
<asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location" />
</Columns>


</asp:GridView>

Any help is most appreciated.

Thanks in advance
Bharath.
GridView with CheckBox – Select All and Highlight Selected Row
Any help appreciated for the below issue:

whenever I click on the checkbox of any particular row, the roe is not highlighting.
I'm using the same function for this(i.e., function HighlightRow(chkB)).

can anyone tell me why it is not highlighting???

Thanks
Bharath.
GridView with CheckBox – Select All and Highlight Selected Row
Hi,
whenever I click on the checkbox of any particular row, the roe is not highlighting.
I'm using the same function for this(i.e., function HighlightRow(chkB)).

can anyone tell me why it is not highlighting???

Thanks
Bharath.
what if odd row and even row in different color?
I have my styling job in gridview_RowCreated event like

protected void ContentGridViewHeader_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Style["font"] = "8pt verdana";
if (e.Row.RowIndex % 2 == 0)
{
e.Row.BackColor = System.Drawing.Color.Tan;

}
else
{
e.Row.BackColor = System.Drawing.Color.YellowGreen;
}
}

Then the javascript can only change back in one color... can the javascript determine odd or even....? Please help...
Thanks
good job
Nice
Just what I was looking for and simple. No custom control needed.
test
good
Greate one, But
Its great one working fentastick but it is not working in firefox mozila.....................

SelectAllCheckboxesSpecific --- this one is not workint in any where, any ways greate work

Cooool....
Thanx! without getting error i got result in first attempt itself.thank you very much...
Very good
Nice code.....
Great
You code is great. Thanks to you.
RE:Great! but jQuery would ease your life
Hi Muhammad, Thanks for your feedback! I will repost the same article with Jquery in future!
Great! but jQuery would ease your life
Thank you for the good article and sample. But I would recommend fi you could do a repost of this article and do it again with jQuery. You'll notice how much jQuery is easy and much faster. And of course less code will be required. Again thank you.