www.MasterCsharp.com Logo  AksTech Ad
 Welcome to MasterCSharp.com - Master C#, the easy way... - by Saurabh Nandu

 

 

Working with CheckBoxes within DataGrid Control
   
 

 

[Rate this Article]
Introduction
Recently I have seen a lot of queries on the newsgroups where people want to create Hotmail like functionality with CheckBoxes within their DataGrid control's. This article should help you sort out these queries.

The problem is that there is a CheckBox in the Header of the DataGrid, just above a column of Checkboxes. Now the functionality required is that when the header CheckBox is selected / deselected relevantly all the CheckBoxes in the column should be selected / deselected. Actually, selection / deselection of CheckBoxes is a client-side scripting activity hence we will have to generate our server-side code in such a way that it can be easily manipulated by client-side scripting.
Another functionality required is that when an external button is clicked we should be able to retrieve all the checked rows from the DataGrid on the server.

Part 1- CheckBox Header

Let's start with the first part of the problem i.e. to deal with working of CheckBox in the header of a CheckBox column. To straight jump to the required functionality, I have used the Pubs database, that's installed with the .NET SDK and MSDE.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<html>

<script language="C#" runat="server">
SqlConnection myConnection;

protected void Page_Load(Object Src, EventArgs E)
{
  myConnection = new SqlConnection("server=(local)\\NetSDK;
			database=pubs;Trusted_Connection=yes");
  if (!IsPostBack)
    BindGrid();
}

public void BindGrid()
{
  SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors",
							myConnection);
  DataSet ds = new DataSet();
  myCommand.Fill(ds, "Authors");

  MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView;
  MyDataGrid.DataBind();
}
</script>

<body style="font: 10pt verdana">

<form runat="server" id="form1" name="form1" >

<h3><font face="Verdana">Working with Checkboxes within a DataGrid</font></h3>

<ASP:DataGrid id="MyDataGrid" runat="server"
      Width="800"
      BackColor="#ccccff"
      BorderColor="black"
      ShowFooter="false"
      CellPadding=3
      CellSpacing="0"
      Font-Name="Verdana"
      Font-Size="8pt"
      HeaderStyle-BackColor="#aaaadd"
      AutoGenerateColumns="false"
    >
 <Columns>

  <asp:BoundColumn HeaderText="au_id"   DataField="au_id" />
  <asp:BoundColumn HeaderText="au_lname"  DataField="au_lname" />
  <asp:TemplateColumn HeaderText="au_fname" >
    <ItemTemplate>
      <asp:Label id="au_fname"
	Text='<%# DataBinder.Eval(Container.DataItem, "au_fname") %>'
	runat="server" />
    </ItemTemplate>
  </asp:TemplateColumn>
  <asp:BoundColumn HeaderText="city"   DataField="city" />

  <asp:TemplateColumn HeaderText="contract" >
    <HeaderTemplate>
      <input type=checkbox id="checkAll"  runat="server">
      Contracts
    </HeaderTemplate>
    <ItemTemplate>
      <input type=checkbox runat="server" id="contract"
 	checked='<%# DataBinder.Eval(Container.DataItem, "contract") %>'/>
    </ItemTemplate>
  </asp:TemplateColumn>
</Columns>
</ASP:DataGrid>
</form>
</body>
</html>

The above code snip should be very familiar to you all by now, I am simply data binding the Authors table from the Pubs database to a DataGrid.
The only advanced functionality here is the definition of custom templates in the DataGrid. Since I want to display the Contract column as a CheckBox column, I use a custom TemplateColumn definition and bind the Boolean database field Contract with the checked property of the HtmlInputCheckBox control defined in the ItemTemplate. Also within the TemplateColumn I have defined a HeaderItem template where I have placed a normal HtmlInputCheckBox control.

A point to note here is that if you want to perform any client-side scripting with your server controls, HtmlControls are the easiest to use, hence I have used the HtmlInputCheckBox control. Also I have data-bound the au_fname field within the ItemTemplate, since I want to retrieve the value this field upon postback in part-2 of this article, but generally you might prefer using the identity column of the table, so that it help's you perform further operations on the selected records.

Next, I change the definition of the HtmlInputCheckBox control in the Header so that it's onclick client-side event calls a JavaScript function CheckAll(). The updated definition of the HtmlInputCheckbox is shown below :


<input type=checkbox id="checkAll"  onclick="CheckAll(this);" runat="server">
 

Now there are many ways you can handle this kind of interaction in JavaScript depending on your solution. Since there can be a lot of permutations of the JavaScript functionality wanted, I will be targeting a common functionality i.e. when the CheckBox in the header is selected / deselected all the CheckBoxes in the column below should check / uncheck respectively. Add the following JavaScript below the DataGrid definition in your code.

Note: I have checked this JavaScript in IE 6.0 and Mozilla 1.0.
 
<script >
var frm = document.form1 ;
function CheckAll( checkAllBox )
{
  var actVar = checkAllBox.checked ;
  for(i=0;i< frm.length;i++)
  {
    e=frm.elements[i];
    if ( e.type=='checkbox' && e.name.indexOf("contract") != -1 )
      e.checked= actVar ;
  }
}
</script>

In the above JavaScript, I first check the state of the CheckBox that fired the event i.e. the header CheckBox. Next, I loop through the form elements searching for all CheckBox controls which have the word "contract" in their name. Always remember that ASP.NET runtime allocates unique names for its controls on the client side, hence you cannot directly use the value of the name attribute you have used while coding your page. Although, the value you provide to the name attribute while defining the control will feature in the client side generated unique id for the control. Hence I am using the indexof function to match the client-side name of the CheckBoxes I want to select. Finally, I set the value of the CheckBoxes to match the value of the Header CheckBox.

This code works correctly, with one minor glitch being that after the Header CheckBox has been selected, which in turn selects all the CheckBoxes in the column and if any CheckBox in the column is later unchecked, the Header CheckBox remains checked! ( Confusing? )
Ideally, the Header CheckBox should only remain checked only if all the CheckBoxes in the column are checked.

To counter this we need to wire-up the column CheckBoxes with another JavaScript function as shown below:
 

<input type=checkbox runat="server" id="contract" onclick="UnCheck();"
checked='<%# DataBinder.Eval(Container.DataItem, "contract") %>'/>
 

Also add the new JavaScript function UnCheck as shown below:
 
function UnCheck()
{
  for(i=0;i< frm.length;i++)
  {
    e=frm.elements[i];
    if ( e.type=='checkbox' && e.name.indexOf("checkAll") != -1 )
    {
      e.checked= false ;
      break;
    }
  }
}

In the above snip of code I just look through the form elements to find the CheckBox in the header and uncheck it.

This finishes the implementation of the first part of this tutorial, now you can save and test the page.

Part 2 - List Checked Rows

Coming to the second part of the article, I will discuss that after the relevant CheckBoxes have been selected there has to be a mechanism, so that on the server-side we know which rows were checked, hence we can perform the relevant operations, usually delete or select.

First we add a Button control to the page as shown below


<asp:button Text="List Selected" runat="server" OnClick="Show_Selected" />
 

And then define its server side event handler as shown below:
 
public void Show_Selected( object sender, EventArgs e)
{
  foreach( DataGridItem di in MyDataGrid.Items )
  {
    HtmlInputCheckBox cb = (HtmlInputCheckBox)di.FindControl("contract") ;
    if( cb !=null && cb.Checked )
    {
      Label lb = (Label)di.FindControl("au_fname");
      Response.Write( lb.Text +"<br>" );
    }
  }
}

In the above method, I loop through each DataGridItem contained within the DataGrid and search for the HtmlInputCheckBox control and then check its value. Later the first names (au_fname) of the Checked rows is printed out using Response.Write. You would be ideally performing some other action based on this selected rows. Two things I would like to instruct at this point,
1) I am printing the values of the au_fname field, since if you remember in the first part I had defined a ItemTemplate for the field. You could also use the DataGridItem's ControlCollection indexer to find the relevant values.
2) The above logic will not work is you have paging enabled in your DataGrid. In that case you will have to check the PageSize and CurrentPage properties of the DataGrid first and only then retrieve values from rows shown on that page.

For your convince I am listing the completely modified source code once again below

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<html>

<script language="C#" runat="server">
SqlConnection myConnection;

protected void Page_Load(Object Src, EventArgs E)
{
  myConnection = new SqlConnection("server=(local)\\NetSDK;
			database=pubs;Trusted_Connection=yes");
  if (!IsPostBack)
    BindGrid();
}

public void BindGrid()
{
  SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors",
							myConnection);
  DataSet ds = new DataSet();
  myCommand.Fill(ds, "Authors");

  MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView;
  MyDataGrid.DataBind();
}

public void Show_Selected( object sender, EventArgs e)
{
  foreach( DataGridItem di in MyDataGrid.Items )
  {
    HtmlInputCheckBox cb = (HtmlInputCheckBox)di.FindControl("contract") ;
    if( cb !=null && cb.Checked )
    {
      Label lb = (Label)di.FindControl("au_fname");
      Response.Write( lb.Text +"<br>" );
    }
  }
}
</script>

<body style="font: 10pt verdana">

<form runat="server" id="form1" name="form1" >

<h3><font face="Verdana">Working with Checkboxes within a DataGrid</font></h3>

<ASP:DataGrid id="MyDataGrid" runat="server"
      Width="800"
      BackColor="#ccccff"
      BorderColor="black"
      ShowFooter="false"
      CellPadding=3
      CellSpacing="0"
      Font-Name="Verdana"
      Font-Size="8pt"
      HeaderStyle-BackColor="#aaaadd"
      AutoGenerateColumns="false"
    >
 <Columns>

  <asp:BoundColumn HeaderText="au_id"   DataField="au_id" />
  <asp:BoundColumn HeaderText="au_lname"  DataField="au_lname" />
  <asp:TemplateColumn HeaderText="au_fname" >
    <ItemTemplate>
      <asp:Label id="au_fname"
	Text='<%# DataBinder.Eval(Container.DataItem, "au_fname") %>'
	runat="server" />
    </ItemTemplate>
  </asp:TemplateColumn>
  <asp:BoundColumn HeaderText="city"   DataField="city" />

  <asp:TemplateColumn HeaderText="contract" >
    <HeaderTemplate>
      <input type=checkbox id="checkAll" onclick="CheckAll(this);" runat="server">
      Contracts
    </HeaderTemplate>
    <ItemTemplate>
      <input type=checkbox runat="server" id="contract" onclick="UnCheck();"
 	checked='<%# DataBinder.Eval(Container.DataItem, "contract") %>'/>
    </ItemTemplate>
  </asp:TemplateColumn>
</Columns>
</ASP:DataGrid>
<asp:button Text="List Selected" runat="server" OnClick="Show_Selected" />

<script >
var frm = document.form1 ;
function CheckAll( checkAllBox )
{
  var actVar = checkAllBox.checked ;
  for(i=0;i< frm.length;i++)
  {
    e=frm.elements[i];
    if ( e.type=='checkbox' && e.name.indexOf("contract") != -1 )
      e.checked= actVar ;
  }
}

function UnCheck()
{
  for(i=0;i< frm.length;i++)
  {
    e=frm.elements[i];
    if ( e.type=='checkbox' && e.name.indexOf("checkAll") != -1 )
    {
      e.checked= false ;
      break;
    }
  }
}
</script>
</form>
</body>
</html>

Conclusion
In this article we saw how to enable client-side JavaScript interaction with CheckBox controls nested within a DataGrid. I hope this article will help you open a few more ideas with the DataGrid control.

 

  
Saurabh Nandu - 01 July 2002


Your Ratings / Comments
     
 

[Go to Top]

How many cups of coffee is this article worth??

Rating (Bad)-(Excellent)

Your Name
Your E-mail  
Your Message (Optional)

Viewer Ratings/Comments
Rating Description
2 gsgfasfs - gggggg on 7/2/2002 7:59:00 PM
Just Comments fsfsfg - dg on 7/4/2002 8:09:00 PM
Just Comments fsfsfg - dg on 7/4/2002 8:14:00 PM
4 - dee on 8/3/2002 2:33:00 AM
3 - h on 8/9/2002 3:53:00 PM
2 - dsffdsq on 10/20/2002 11:04:00 AM
5 - Laude on 1/3/2003 7:38:00 PM
1 testing - asdf on 3/4/2003 4:21:00 PM
1 - asd on 3/28/2003 1:57:00 PM
4 dh - hd on 4/10/2003 11:50:00 PM
1 Why me - errew on 5/4/2003 10:48:00 AM
2 zxccvbbcvb c - zsdc on 5/10/2003 7:02:00 PM
2 sissks - adas on 6/5/2003 2:32:00 PM
5 jfgjfgjfg - dfdg on 7/2/2003 3:29:00 PM
1 11 - 11 on 7/7/2003 2:25:00 PM
Just Comments asdasdasd - az on 9/16/2003 3:54:00 PM
3 - j on 9/17/2003 7:51:00 PM
3 test - Michael on 9/25/2003 3:39:00 PM
5 afdafdgfghghggj - xyz on 9/26/2003 9:33:00 AM
5 - Justin on 11/8/2003 5:12:00 PM
1 ggg - james on 12/7/2003 12:26:00 AM
1 ewewe - we on 2/14/2004 2:57:00 AM
2 - rajaee on 3/1/2004 4:54:00 AM
1 my message - noone on 4/1/2004 9:59:00 AM
2 so good! - tun on 4/10/2004 1:30:00 AM
4 - ezrtz on 4/13/2004 10:55:00 AM
5 - lastentry on 5/18/2004 11:32:00 AM
2 - ? on 6/16/2004 10:23:00 PM
2 asd - a on 7/27/2004 3:26:00 AM
1 ??????? - ????? on 8/5/2004 3:53:00 AM
3 good one ! - sandar lin on 8/9/2004 9:41:00 AM
3 Nice - P.Nishanthan on 8/21/2004 6:51:00 AM
1 hai - suresh on 8/31/2004 11:42:00 PM
5 - Oguz Yilmaz on 9/27/2004 10:47:00 AM
1 gfhgf - hfghfg on 11/12/2004 3:56:00 PM
3 sdf - sdf on 1/10/2005 3:44:00 AM
2 admin - admin on 2/2/2005 4:36:00 AM
1 Yes - sekhar on 2/11/2005 5:27:00 AM
5 - shenzuofeng on 2/17/2005 9:36:00 PM
2 - aa on 4/29/2005 3:51:00 AM
Just Comments - fdgb on 5/9/2005 6:02:00 AM
1 good - ddd on 5/12/2005 7:58:00 AM
2 fsdf - eeeee on 7/13/2005 1:53:00 AM
5 Nice - umakant on 7/16/2005 5:19:00 AM
2 ghgfhgfhg - ffgh on 7/26/2005 2:14:00 AM
2 Good - Prashant Doifode on 8/3/2005 5:32:00 AM
3 good one - pathan sajid ali khan on 8/4/2005 1:55:00 AM
2 can we get the same in VB.NET - AJAY on 8/18/2005 5:56:00 AM
2 cvbcvbc - das on 9/22/2005 6:59:00 AM
3 das - sdfs on 9/22/2005 7:00:00 AM
4 - gman on 10/2/2005 8:32:00 AM
Just Comments aahaa Oohooo - lv on 10/28/2005 5:55:00 AM
3 Good - Naresh on 1/10/2006 6:51:00 AM
Just Comments - 1 on 1/19/2006 10:25:00 PM
3 good - prashant raizada on 8/19/2006 11:04:00 AM
Just Comments dcfsdf - sdasdas on 8/28/2006 10:46:00 AM
5 - 3 on 9/5/2006 1:25:00 AM
5 It's helpful...Thkx - Melissa.C on 9/7/2006 2:13:00 AM
3 nice one - kalyan on 9/15/2006 3:29:00 AM
Just Comments fsadfsdfsadfasdf - amit on 9/26/2006 2:18:00 AM
1 fdfdsf sdf dsf dsf dsf dsf dsf ds - dmukundi on 9/26/2006 5:38:00 AM
Just Comments adasdasd asdsa das das dsad ads asd sad sadsa - dmukundi on 9/26/2006 5:39:00 AM
4 nothing...but true - jagmohan on 9/29/2006 4:09:00 AM
5 good article - sandeep on 10/6/2006 12:49:00 AM
2 - amit on 10/17/2006 1:20:00 AM
4 - ADRIAN STANESE on 10/24/2006 9:49:00 AM
2 average - saravanan on 10/31/2006 2:25:00 PM
4 Very Basic but Nice one ... :) Thanks - Saravanakumar on 11/7/2006 12:08:00 AM
1 Hello, I tried using this code you provided. There's an error with it. The datagrid is not showing...why is that happening? When i click the view source of the page...this is what i get.... <HTML> <body style="FONT: 10pt verdana"> <form name="form1" method="post" action="WebForm1.aspx" id="form1"> <input type="hidden" name="__VIEWSTATE" value="dDw0MzQ1MjE5MTg7dDw7bDxpPDI+Oz47bDx0PDtsPGk8MT47PjtsPHQ8QDA8Ozs7Ozs7Ozs7Oz47Oz47Pj47Pj47Pgbk/b2QYg0t868TOrA9sZ+ic9TF" /> <h3><font face="Verdana">Working with Checkboxes within a DataGrid</font></h3> <input type="submit" name="Button1" value="List Selected" id="Button1" NAME="Button1" /> <script> var frm = document.form1 ; function CheckAll( checkAllBox ) { var actVar = checkAllBox.checked ; for(i=0;i< frm.length;i++) { e=frm.elements[i]; if ( e.type=='checkbox' && e.name.indexOf("contract") != -1 ) e.checked= actVar ; } } function UnCheck() { for(i=0;i< frm.length;i++) { e=frm.elements[i]; if ( e.type=='checkbox' && e.name.indexOf("checkAll") != -1 ) { e.checked= false ; break; } } } </script> </form> </body> </HTML> - Byock on 11/7/2006 11:41:00 PM
Just Comments This is really cool stuff,i tried it .its working fine.no probs - Umamahesh on 11/13/2006 9:24:00 PM
5 Hello, I used your code in checkin and uncheckin the checkboxes in my datagrid...now after selecting all or some checkboxes in the grid i need to click a button that will edit something on the items selected in the datagrid via the checkboxes... Now after clicking the button, i need the page to refresh...and show the edited items with their new values? So how will i refresh the page? Thank you. - Byock on 12/11/2006 1:46:00 AM
5 Great piece of code. Just exactly what was needed. - David Hippensteel on 12/29/2006 9:06:00 AM
5 Excellent - jayanthi on 1/4/2007 5:33:00 AM
3 Hyderabad - Narsi on 1/17/2007 4:09:00 AM
3 Good Artice.Can you provide the code for batch updating - Sri Harsha on 1/17/2007 9:06:00 PM
2 - jjjjjj on 1/20/2007 1:51:00 AM
2 hi - khan on 1/25/2007 12:10:00 AM
Just Comments 9866873700 - P.Dadapeern khan on 1/25/2007 12:12:00 AM
2 erwrwrwrwrwr - jana on 1/27/2007 11:35:00 AM
3 can u give me the detail program code in database connectivity with asp.net & c#. - Abinash Kumar on 2/2/2007 10:04:00 AM
5 - nallam on 2/14/2007 10:57:00 PM
5 sdf - dfs on 2/26/2007 10:48:00 PM
5 very nice reference.. - parker on 3/5/2007 6:18:00 AM
5 asasdasdjasodjoasjdoasdoijasd - qaas on 3/15/2007 4:12:00 AM
1 gdg - bv bc on 3/22/2007 10:15:00 PM
1 ASDf - dsgf on 4/9/2007 10:58:00 PM
1 tyry - tdr on 4/29/2007 10:54:00 PM
5 This is great code - Paul on 5/3/2007 4:05:00 AM
1 Amigo muchas gracias, de verdad gracias, solucione mi problema - omar on 5/15/2007 10:37:00 AM
1 lee3 - lee1 on 6/24/2007 7:26:00 AM
3 ya it is very good - Durgaprasad(Naresh tecnologies ,HYD) on 7/12/2007 10:33:00 AM
4 gud - pppp on 8/6/2007 10:58:00 PM
1 UploadPhoto1 - UploadPhoto1 on 8/13/2007 4:47:00 AM
1 Conclusion In this article we saw how to enable client-side JavaScript interaction with CheckBox controls nested within a DataGrid. I hope this article will help you open a few more ideas with the DataGrid control. - Conclusion on 8/13/2007 4:52:00 AM
5 This Is very good Article - Samarjeet Doifode on 8/24/2007 4:15:00 AM
5 Its good for developer to provide such information - Manoj on 9/24/2007 2:12:00 AM
3 easfsdf - 345 on 9/28/2007 3:24:00 AM
1 dfdfdfdfdfdfdfdfddfdfd - llk;lk on 10/11/2007 4:51:00 AM
5 very nice article - doesn't matter on 11/14/2007 11:25:00 AM
Just Comments gud but hard to understand - Neetu on 11/21/2007 4:31:00 AM
3 If the screen shots of the page added, it would be better. - Arun on 11/25/2007 9:23:00 PM
1 nt bad - lekha on 2/4/2008 11:01:00 PM
Just Comments - on 3/10/2008 11:48:00 PM
4 good for begining - ravi on 5/14/2008 6:26:00 AM
1 dfgf - medikonda on 11/22/2008 6:51:00 AM

[Go to Top]


 
 
  Copyright © 2002 - 2004 MasterCSharp.com. All rights are reserved.

  Presenting MasterCSharp.com in association with AksTech Solutions - .NET Solutions Development and Consulting. 

  Best Viewed in IE 4.0+ and 800x600 Resolution