Check/Un-Check checkboxes items in ASP.NET DataGrid using JavaScript


In this article we will see how to check and un-check checkboxes items in ASP.NET DataGrid using JavaScript. We will also see how to delete all checked items and to change Datagrid row background color on mouse over.

1.gif
 
Code:

<asp:DataGrid ID="MyDataGrid" AutoGenerateColumns="false" runat="server"
           AllowPaging="true" PagerStyle-Mode="NextPrev"
           onitemdatabound="MyDataGrid_ItemDataBound" ShowFooter="true"
           onpageindexchanged="MyDataGrid_PageIndexChanged" PageSize="4"
           onitemcommand="MyDataGrid_ItemCommand" Width="100%">
<Columns>
  <asp:BoundColumn HeaderText="CustomerId" DataField="CustomerId"></asp:BoundColumn>
  <asp:BoundColumn HeaderText="Name"  DataField="Name"></asp:BoundColumn>
  <asp:BoundColumn HeaderText="City"  DataField="City"></asp:BoundColumn>
  <asp:BoundColumn HeaderText="Mobile"  DataField="Mobile"></asp:BoundColumn>
  <asp:BoundColumn HeaderText="Address"  DataField="Address"></asp:BoundColumn>
  <asp:BoundColumn HeaderText="Date Of Birth" DataFormatString="{0:MM/dd/yyyy}" DataField="DOB"></asp:BoundColumn>
  <asp:TemplateColumn>
      <ItemTemplate>
        <asp:CheckBox ID="cbRows" runat="server"/>
      </ItemTemplate>
      <HeaderTemplate>
        <input type="checkbox" id="mainCB" onclick="javascript:CheckAll(this);" />
      </HeaderTemplate>
      <FooterTemplate>
        <asp:Button ID="btnDelete" runat="server" Text="Delete"   OnClick="Button1_Click"   OnClientClick="return DeleteConfirmation();"/>
      </FooterTemplate>
  </asp:TemplateColumn>
   <asp:ButtonColumn  ButtonType="PushButton" CommandName="Update" Text="Edit"></asp:ButtonColumn>
  </Columns>
</asp:DataGrid>

JavaScript:

<script type="text/javascript" language="javascript">
function CheckAll(chk)
{
all = document.getElementsByTagName("input");
for(i=0;i<all.length;i++)
    {
      if(all[i].type=="checkbox" && all[i].id.indexOf("MyDataGrid_ct") > -1)
      {
        all[i].checked = chk.checked;
      }
    }
}
function DeleteConfirmation()
{
if (confirm("Are you sure, you want to delete selected records ?")==true)
   return true;
else
   return false;
}
</script>

.Net Code:

public void BindGrid()
{
    DataSet ds = Customer.GetCustomers();
    MyDataGrid.DataSource = ds;
    MyDataGrid.DataBind();
}
//Delete Button
protected void Button1_Click(object sender, EventArgs e)
{
    foreach (DataGridItem item in MyDataGrid.Items)
    {
        if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
        {
            if (((CheckBox)item.Cells[6].FindControl("cbRows")).Checked)
            {
                Customer.DeleteMe(Convert.ToInt32(item.Cells[0].Text));
            }
        }
    }
    BindGrid();
}

Up Next
    Ebook Download
    View all
    Learn
    View all