title: Select all checkboxes in gridview from button client side
body: <p>I have a gridview with rows containing a checkbox. Below the gridview I have a button. When I click it I want to select all the checkboxes from client side. So far I've read about OnClientClick, javascript and so on.. but my code doesn't work. Can someone help me out please?</p>
  
  <p>note: I don't wanna select the checkboxes selecting the checkbox in the header (I found a lot of examples about this), but clicking a button outside the gridview</p>
  
  <pre><code> &lt;asp:GridView runat="server"  ID="MyGridView" EnableViewState="true" 
      AutoGenerateColumns="False" 
      &gt;&lt;AlternatingRowStyle BackColor="White" /&gt;
  
      &lt;Columns&gt;
  
      &lt;asp:TemplateField HeaderText="Select" SortExpression="Select" ItemStyle-HorizontalAlign="Center" &gt;
                  &lt;EditItemTemplate&gt;
                      &lt;asp:CheckBox ID="CkBoxSelectET" runat="server" /&gt;&lt;/EditItemTemplate&gt;
                  &lt;ItemTemplate&gt;
                      &lt;asp:CheckBox ID="CkBoxSelectIT" runat="server" /&gt;&lt;/ItemTemplate&gt;
         &lt;/asp:TemplateField&gt;
  
         &lt;asp:TemplateField HeaderText="Name" SortExpression="Name" ItemStyle-HorizontalAlign="Center" Visible="false" &gt;
                  &lt;ItemTemplate&gt;
                      &lt;asp:Label ID="name" runat="server" Text='&lt;%# Bind("Name") %&gt;' Visible="false" /&gt;&lt;/ItemTemplate&gt;
          &lt;/asp:TemplateField&gt;
  
          &lt;asp:TemplateField HeaderText="City" SortExpression="City" ItemStyle-HorizontalAlign="Left" &gt;
                  &lt;ItemTemplate&gt;
                      &lt;asp:Label ID="lblCity" runat="server" /&gt;&lt;/ItemTemplate&gt;
          &lt;/asp:TemplateField&gt;
  
      &lt;/Columns&gt;
      &lt;/asp:GridView&gt;
  
  &lt;asp:Button runat="server" ID="btnSelect" Text="Select all" BackColor="LightGray" OnClientClick="SelectAll(id);" /&gt;
  
  &lt;script type="text/javascript"&gt;
  
  var gridViewControl = document.getElementById('&lt;%= MyGridView.ClientID %&gt;');
  
  function SelectAll(id) {
      for (i = 0; i &lt; gridViewControl.elements.length; i++) {
          if (gridViewControl.elements[i].type == "checkbox") {
              gridViewControl.elements[i].checked = document.getElementById(id).checked;
          }
      }
  } 
  </code></pre>
  
  <p></p>
  
  <p>in c#, when i bind the data:</p>
  
  <pre><code> btnSelect.Attributes.Add("OnClientClick", "javascript:SelectAll('" + btnSelect.ClientID + "')");
  </code></pre>