Implement check all checkbox functionality in ASP.Net GridView control using JavaScript
I am explaining how to make use JavaScript check box in gridview.
I have a gridview with id="grdata" and bind from database like below code
Aspx Part:-
Now i add a javascript funcation with name "CheckAllEmp" which are call in gridview checkbox control.
javascript funcation like this
<script type="text/javascript" language="javascript">
function CheckAllEmp(Checkbox) {
var GridVwHeaderChckbox = document.getElementById("<%=grdata.ClientID %>");
for (i = 1; i < GridVwHeaderChckbox.rows.length; i++) {
GridVwHeaderChckbox.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked
= Checkbox.checked;
}
}
</script>
This is gridview aspx code which are binding from database
<asp:GridView runat="server" ID="grdata" AutoGenerateColumns="false" DataKeyNames="UserName" AllowPaging="True" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkHeader" runat="server" onclick="CheckAllEmp(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chck" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label runat="server" ID="lblName" Text='<%#Eval("Name")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile">
<ItemTemplate>
<asp:Label runat="server" ID="lblMobile" Text='<%#Eval("Mobile") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label runat="server" ID="lblid" Text='<%#Eval("UserName") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:Label runat="server" ID="lblAddress" Text='<%#Eval("Address") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label runat="server" ID="lblEmail" Text='<%#Eval("emailid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS Code Part:-
void bind()
{
try
{
Connection.con.Open();
SqlCommand cmd = new SqlCommand("select * from table order by id desc", Connection.con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if
(dt.Rows.Count > 0)
{
grdata.DataSource = dt;
grdata.DataBind();
}
else
{
dt.Rows.Add(dt.NewRow());
grdata.DataSource = dt;
grdata.DataBind();
int
count = grdata.Rows[0].Cells.Count;
grdata.Rows[0].Cells.Clear();
grdata.Rows[0].Cells.Add(new TableCell());
grdata.Rows[0].Cells[0].ColumnSpan = count;
grdata.Rows[0].Cells[0].Text = "There is no record in your
DataBase..";
}
}
catch
(Exception ex)
{
finally
{
Connection.con.Close();
}
}
This method call on page load like this
protected void Page_Load(object sender, EventArgs e)
{
if
(!IsPostBack)
{
bind();
}
}
No comments:
Post a Comment