Thursday, May 19, 2011

Check and uncheck all checkbox in GridView using JavaScript.


This is one of the most common query I saw in Microsoft forums when a beginner start coding. So I thought I will take some time and post a simple and useful code here.
 
<html>
<head id="Head1" runat="server">
  <title>Untitled Page</title>
  <script type="text/javascript">
      function CheckAllRow(chkBox) {
          var gridViewCtlId = '<%=GridView1.ClientID%>';
          var grid = document.getElementById(gridViewCtlId);
          var gridLength = grid.rows.length;
          for (var i = 1; i < gridLength; i++) {
              cell = grid.rows[i].cells[1];
              for (var j = 0; j < cell.childNodes.length; j++) {
                  if (cell.childNodes[j].type == 'checkbox') {
                      cell.childNodes[j].checked = chkBox;
                  }
              }
          }
      }
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:LinkButton ID="chkAll" Text="Check all" OnClientClick=" CheckAllRow(true); return false;"
      runat="server"></asp:LinkButton><br />
    <asp:LinkButton ID="lnkUncheck" Text="Uncheck all" OnClientClick=" CheckAllRow(false); return false;"
      runat="server"></asp:LinkButton><br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AutoGenerateSelectButton="True"
       OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
      OnDataBound="GridView1_DataBound" OnRowDataBound="GridView1_RowDataBound">
      <Columns>
        <asp:TemplateField>
          <HeaderTemplate>
            Select All
            <asp:CheckBox ID="chkBoxAll" runat="server" onclick="CheckAllRow(this.checked);" />
          </HeaderTemplate>
          <ItemTemplate>
            <asp:CheckBox ID="chkBoxSel" runat="server" />
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Course ID">
          <ItemTemplate>
            <%# Eval("ID") %>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Course Name">
          <ItemTemplate>
            <%# Eval("Name")%>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Title">
          <ItemTemplate>
            <%# Eval("Address")%>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Description">
          <ItemTemplate>
            <%# Eval("Phone")%>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Course Type">
          <ItemTemplate>
            <%# Eval("Description") %>
          </ItemTemplate>
        </asp:TemplateField>
      </Columns>
    </asp:GridView>
  </div>
  </form>
</body>
</html>

1 comment:

Anonymous said...

nice ..