title: Limiting number of checkboxes selected in gridview in c#
body: <p>I need limiting the number of checkboxes selected by user on the GridView in c# asp net.</p>
  
  <p>I tried the code below but I have two problems:</p>
  
  <ol>
  <li>After alert popup <strong><code>'Cannot check more than 3 check boxes'</code></strong> the Checkbox number four is always selected;</li>
  <li>The button <strong><code>btn</code></strong> is enabled and validate the form.</li>
  </ol>
  
  <p>What am I missing?</p>
  
  <p>What's wrong with this code?</p>
  
  <p>Thank you in advance.</p>
  
  <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %&gt;
  
  &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
  &lt;head runat="server"&gt;
      &lt;title&gt;&lt;/title&gt;
      &lt;script type="text/javascript"&gt;
          function CheckCheck() {
              var chkBoxList = document.getElementById('&lt;%=GridView1.ClientID %&gt;');
              var chkBoxCount = chkBoxList.getElementsByTagName("input");
  
              var btn = document.getElementById('&lt;%=btn.ClientID %&gt;');
              var i = 0;
              var tot = 0;
              for (i = 0; i &lt; chkBoxCount.length; i++) {
                  if (chkBoxCount[i].checked) {
                      tot = tot + 1;
                  }
              }
  
              if (tot &gt; 3) {
                  alert('Cannot check more than 3 check boxes');
              }
          }
  
      &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;form id="form1" runat="server"&gt;
      &lt;div&gt;
          &lt;asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"&gt;
              &lt;Columns&gt;
                  &lt;asp:TemplateField&gt;
                      &lt;ItemTemplate&gt;
                          &lt;asp:CheckBox ID="cbSelProduct" runat="server" onclick="javascript:CheckCheck();" /&gt;
                          &lt;asp:HiddenField ID="HiddenField1" runat="server" Value='&lt;%#Eval("name")%&gt;' /&gt;
                      &lt;/ItemTemplate&gt;
                  &lt;/asp:TemplateField&gt;
                  &lt;asp:BoundField ItemStyle-Width="250px" DataField="name" HeaderText="name" /&gt;
              &lt;/Columns&gt;
          &lt;/asp:GridView&gt;
          &lt;asp:Button runat="server" ID="btn" Text="Send" OnClick="btn_Click" /&gt;
      &lt;/div&gt;
      &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>