Select All CheckBox in Gridview ASP.NET

12. February 2009

I don't know how many examples they are of this, but this is how I went about doing this.  I'm sure there are many articles, but I felt like writing something today so here it is.  It's useful as it is. I was coding in VB so this is VB.NET example.  You can just get rid of the "Me." if you want in the javascript code.

Javascript code
function checkAllBoxes(){

  //get total number of rows in the gridview and do whatever
  //you want with it..just grabbing it just cause
  var totalChkBoxes = parseInt('<%= Me.gvTest.Rows.Count %>');   
  var gvControl = document.getElementById('<%= Me.gvTest.ClientID %>');
           
  //this is the checkbox in the item template...this has to be the same name as the ID of it
  var gvChkBoxControl = "chkBoxChild";  
           
  //this is the checkbox in the header template
  var mainChkBox = document.getElementById("chkBoxAll");
           
  //get an array of input types in the gridview
  var inputTypes = gvControl.getElementsByTagName("input");
           
  for(var i = 0; i < inputTypes.length; i++)
  {  
     //if the input type is a checkbox and the id of it is what we set above
     //then check or uncheck according to the main checkbox in the header template            
     if(inputTypes[i].type == 'checkbox' && inputTypes[i].id.indexOf(gvChkBoxControl,0) >= 0)
          inputTypes[i].checked = mainChkBox.checked;  
  }
}

Gridview Code
As you can see it's a very trimmed down version because the important part is the header template and item template for the first column

<asp:GridView ID="gvTest" runat="server" AutoGenerateColumns="false">
 <Columns>
   <asp:TemplateField>
       <HeaderTemplate>
         <input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()" />
       </HeaderTemplate>
       <ItemTemplate>
         <asp:CheckBox ID="chkBoxChild" runat="server" />
       </ItemTemplate>
   </asp:TemplateField>
   <!-- The rest of your rows here -->
 </Columns>
</asp:GridView>

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

ASP.NET ,

blog comments powered by Disqus