Skip to main content

Simultaneous selection(deselection) all checkboxes in a GridView's column


14 Mar 2008 If you are using checkboxes in GridView in order to select a few rows, then, no doubt, you have been faced with the task how to select/deselect all checkboxes in a selected column at a time. Usually it is solved by addition of special buttons somewhere or addition a checkbox in the GridView's column header.
I want to dwell on the second variant. In order to refrain from repetition of code all of required functionality can be hidden inside of a special control. This control is inherited from the CheckBox and have only one method overriden (OnLoad). Inside the method a script is registered, this script allows to select/deselect all checkboxes in a GridView's column if a checkbox in the GridView's header is clicked. Besides, the script tracks situation when all checkboxes in rows are selected one by one and selects the checkbox in the column's header.
public class GridViewCheckBox : CheckBox
{
  protected override void OnLoad(EventArgs e)
  {
    GridViewRow parentRow = this.NamingContainer as GridViewRow;

    //checks whether the checkbox is inside of a template column (TemplateField)
    if (parentRow != null)
    {
        //registers the script
        string script = @"function gvCheckBoxClicked(sender,isHeader) {
 var cell = sender.parentNode;
 var rows = cell.parentNode.parentNode.rows;
 if (isHeader) {
     for(i=1; i<rows.length; i++)
        rows[i].cells[cell.cellIndex].getElementsByTagName(""input"")[0].checked = sender.checked;
 }
 else {
    var headerCheckBox = rows[0].cells[cell.cellIndex].getElementsByTagName(""input"")[0];
    if (!sender.checked)
         headerCheckBox.checked = false;
    else {   
          for(i=1; i<rows.length; i++) {
               if (!rows[i].cells[cell.cellIndex].getElementsByTagName(""input"")[0].checked) {
                    headerCheckBox.checked = false;
                    return;
              }
     }
     headerCheckBox.checked = true;
           }
    }
}";

        if (!Page.ClientScript.IsClientScriptBlockRegistered(typeof(Page), "GridViewCheckBox"))
            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "GridViewCheckBox", script, true);

        //adds onclick event handler
        if (parentRow.RowType == DataControlRowType.Header)
            this.Attributes["onclick"] = "gvCheckBoxClicked(this,true);";
        else if (parentRow.RowType == DataControlRowType.DataRow)
            this.Attributes["onclick"] = "gvCheckBoxClicked(this,false);";
    }

    base.OnLoad(e);
 }
}
That is all. In order to use just add the control to HeaderTemplate and ItemTemplate of the required column:
<asp:GridView ID="GridView1" runat="server" >
   <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <wc:GridViewCheckBox id="GridViewCheckBox1" runat="server"/>
            </HeaderTemplate>
            <ItemTemplate>
                <wc:GridViewCheckBox id="GridViewCheckBox2" runat="server"/>
            </ItemTemplate>
       </asp:TemplateField>
       <asp:BoundField ...
       ...
   </Columns>
</asp:GridView>
This is an illustration (clickable).
Author Name
Stephen Walther ASP.NET 3.5 Unleashed
Marco Bellinaso ASP.NET 2.0 Website Programming: Problem - Design - Solution (Programmer to Programmer)
Omar AL Zabir Building a Web 2.0 Portal with ASP.NET 3.5
Dino Esposito Microsoft ASP.NET 3.5 Developer Reference
Matthew MacDonald, Mario Szpuszta Pro ASP.NET 3.5 in C# 2008, Second Edition

Comments

Popular posts from this blog

Dynamic Generation of Word Document Report in ASP.NET with HTML

Overview Ever needed to generate Word documents from your ASP.NET applications? There are a couple of components which will help to generate Word documents, but using these components may have some overhead such as Component Registration, setting permissions, licenses, etc., Sometimes, it may even become difficult to understand their features and use them. Generating word document in ASP.NET with HTML is incredibly easy. The following sample demonstrates how to place Heading and Table dynamically in the word document in ASP.NET web applications using HTML. Requirements Microsoft Visual Web Developer 2005 Express Edition Create the Web Application project Add the new Web Site Application project (with name as Generate Word Document) and place the button (with name as btnGenerateDocument) in the Default.aspx web form as shown below. Double click the highlighted code behind file from the Solution Explorer and add the following namespaces. Listing 1 using  System...

GRIDVIEW ZOOM IMAGE

When you have images in your  GridView , you would most likely show them as thumbnails so as to not distort the whole layout. However user would want to look at the full image by clicking on the image or just hovering his mouse over it. In today’s applications, this is a basic requirement and there are just so many third party controls or plugins which would support this functionality. I am going do this conventional way using  javascript  way in this article.  On top of it, I am also going to explain how to get images from database using  HttpHandlers . Example: I am using  Adventure Works  as datasource. We fetch handful of products and bind them to the grid. When page is initially loaded, we retrieve products from Production . Product  table and bind them to the grid. We display some product attributes such as Product ID, Product Number, Product Name, List Price and product’s thumbnail. When user hover his mouse on the page, we fetch the f...

GRIDVIEW GROUPING

When displaying data, we sometimes would like to group data for better user experience or when displaying long list of hierarchal data, we would want to display them in a tree view kind of structure. There is more than way of doing this, but I am going to explain achieving this functionality using  AJAX Collapsible Panel Extender Control . Overview: I am going to use  Adventure Works  as datasource. Every product in  Production.Product  table belongs to a product sub category. We fetch handful of products and the sub categories they belong to from the database. Our objective is to list all the available sub categories and allow user to  expand/collapse  to look/hide the list of products belonging to each subcategory. Database Connection Added following entry under  connectionStrings  element in  web.config . < add   name = "Sql"   connectionString="Data Source=(local); Initial  Catalog = AdventureWorks ...