Asp.Net Library

Wednesday, September 24, 2008

How to Check all checkboxes in a GridView

In this article we will discuss in how to fire all checkBoxes in gridview at once , we need to do that when deleting all rows in gridView .

So let's start to do this task

1- Add SqlDataSource for conection to dataBase in this example we use AdventureWorksDW database .


<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksDWConnectionString %>"
SelectCommand="SELECT [FirstName] FROM [DimEmployee]"></asp:SqlDataSource>

2- after drag the gridview in Asp.net page change the property of AutoGenerateColumns to false



<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="442px" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="ChkAll" runat="server" AutoPostBack="True"
oncheckedchanged="Chk_CheckedChanged" Text="Check All" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("FirstName") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>




3- Now we have 2 checkboxes inside gridview the first on for check or uncheck all rows and the 2nd for check or un check per row.


4- double click on 'chkAll' checkBox and write this code :





protected void Chk_CheckedChanged(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
CheckBox chkSelect = ((CheckBox)row.FindControl("chkSelect"));
if (((CheckBox)sender).Checked == true)
{
chkSelect.Checked = true;
}
else
{
chkSelect.Checked = false;
}
}
}

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home