July 04 2009

Master CheckBox in GridView header

Introduction

Its common to show records from database table with GridView in ASP.Net. Once we disply records, we need to do some actions which will be applied to one, many or all records,lets say “Bulk Actions”. So we need to have a way to select records ( one or many or all ), and perform required action.

For example I am going to show all products from NorthWind database and then I will select some of them to delete or modify. The best solution in this case would be nice to have a column with CheckBox in the GridView. But if I will have 100 records in my table and I want to select all, it would be a big work for me to go and select them one by one. So lets have a master CheckBox in the header of CheckBox column.

So I am going to add a CheckBox column, with a CheckBox in header, And then use jQuery to check/un-check all of them

Setting jQuery in an ASP.NET web site

Its quite easy to set jQuery to use in ASP.NET. Put the latest Scripts in your project and reference them on your page or Master page. Doing that in Master Page is a very good option. Check the attached code for it. I am going to use ScriptManager to reference jQuery script file.

Lets Implement It!

First of all I need to show all the products in an GridView. That will be very simple. And I coded this -

<asp:SqlDataSource ID="sdsProducts" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [UnitsOnOrder] FROM [Alphabetical list of products]">
</asp:SqlDataSource>
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
DataSourceID="sdsProducts">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<input id="masterCheck" type="checkbox" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" SortExpression="QuantityPerUnit" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" SortExpression="UnitsOnOrder" />
</Columns>
</asp:GridView>

I am using SQLDataSource and a GridView to Display Records.
Note that first column is a template column. In header of this column, I am using a normal HTML checkbox with an id “masterCheck”. And then an asp.net CheckBox in itemplate, with an id “chkSelect” .

<asp:TemplateField>
<HeaderTemplate>
<input id="masterCheck" type="checkbox" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect" />
</ItemTemplate>
</asp:TemplateField>

So outcome will be a GridView with product list.
Products

Execute the page and check its HTML source. You will notice that id of master checkbox is same as what we have given i.e “masterCheck”. But the checkboxes in ItemTemplate will have ids like “ctl00_myBody_gvProducts_ctl02_chkSelect”. This is ASP.NET name mangling. It is going to decide how I will use jQuery selector expression.

Now we need to write jQuery code, which will Check/Un-Check all checkboxes. So I will following things
1. Find my master checkbox in gridview.
2. Attach handler for click event of master checkbox.
3. I will find all the checkboxes with id ending with “chkSelect” and assign checked state of master checkbox to them.

So this will be jQuery code produced -

<script language="javascript" type="text/javascript">
$(document).ready(function() {
  $("#masterCheck").click(function() {
    $("[id$=chkSelect]").attr('checked', $('#masterCheck').is(':checked'));
  });
});

</script>

Here is an explanation of line by line
1. Write code in document.ready event
2. Get the master checkbox and attach a function to its “click” event.
3. Find all checkboxes whoose ids are ending with “chkSelect”. I need to do this because of ASP.NET name mangling.
4. Assign checked state of master checkbox to selected checkbox.

And thats all. Once you have selected all or none, you press any button like edit, delete or hide to perform a postback. In your code behind you can loop through rows of GridView and get the values of checkbox. For example I am going to prepare a string of IDs separated by commas and display them. Check the event handler code for show button -


protected void btnShow_Click(object sender, EventArgs e)
{
  StringBuilder IDs = new StringBuilder();
  int count = gvProducts.Rows.Count;

 for (int i = 0; i < count; i++)
 {
     CheckBox chkSelect = gvProducts.Rows[i].FindControl("chkSelect") as CheckBox;
     if (chkSelect.Checked)
    {
       IDs.Append(gvProducts.DataKeys[i].Value);
       IDs.Append(",");
    }
 }
}

Conclusion

So I have used jQuery to check and un-check all the checkboxes in my GridView column. For this I am using a master checkbox with an id “masterCheck”,  and attached its click event to a function which will find all the CheckBoxes with id ending with “chkSelect”.  Once I have checkboxes, I will assign checked state of masterCheck to them. You can change master check box to ASP.NET control also, if you need to manipulate it from server side.

Happy Programming!

Update on 13-October-2009
After so many requests for both side check and un-check, I have updated the code. Now when you un-check a child checkbox, it will check or uncheck the master checkbox also ( if all are checked or un checked).
New code is


<script language="javascript" type="text/javascript">
	// for master checkbox
	$(document).ready(function() {
		$("#masterCheck").click(function() {
			isChecked = $(this).is(':checked');
			$("[id$=chkSelect]", $("#<%= gvProducts.ClientID %>")).attr('checked', isChecked);
		}
		);
	});

	// for checkboxes in GridView
	$(document).ready(function() {
		$("[id$=chkSelect]", $("#<%= gvProducts.ClientID %>")).click(function() {
			$("#masterCheck").attr('checked', allAreChecked);
		});
	});

	function allAreChecked() {
		var allCheckBoxesCount = $("[id$=chkSelect]", $("#<%= gvProducts.ClientID %>")).length;
		var allCheckedCheckBoxesCount = $("[id$=chkSelect]:checked", $("#<%= gvProducts.ClientID %>")).length;

		return (allCheckBoxesCount == allCheckedCheckBoxesCount);
	}

</script>

Attached Files:

Comments:

(21) posted on Master CheckBox in GridView header

Post a comment

Spam protection by WP Captcha-Free

RSS