ASP C# CheckBox within DetailsView

313 views Asked by At

I have a DetailsView in my aspx page with two check boxes in item template columns. I have a buttoun outside DetailsView. What i need is when i click button it should verify whether both checkboxes are checked and fire c# command. please help. Let me paste Code below:

.aspx

 <div>
        <asp:Button ID="Button3" runat="server" Text="Button" OnClick="Button3_Click" />
    </div>
    <asp:DetailsView ID="DetailsView2" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataSourceID="SqlDataSource2">
        <Fields>
            <asp:TemplateField HeaderText="StudentName" SortExpression="StudentName">
                <ItemTemplate>
                     <asp:CheckBox ID="CheckBox1" runat="server" />
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("StudentName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Email" SortExpression="Email">

                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox2" runat="server" />
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Fields>
    </asp:DetailsView>

C#

 protected void Button3_Click(object sender, EventArgs e)
    {

    }
1

There are 1 answers

0
Koby Douek On

A DetailsView is a data bound control which can hold an unlimited number of rows, not just one.

If you want to verify both checkboxes are checked, in each row, you would need to iterate through all of the DetailsView's rows, and cast the CheckBox from FindControl on each row:

protected void Button3_Click(object sender, EventArgs e)
{
    for (int i = 0; i < DetailsView2.Rows.Count; i++)
    {
        CheckBox chk1 = (CheckBox)DetailsView2.Rows[i].FindControl("CheckBox1");
        CheckBox chk2 = (CheckBox)DetailsView2.Rows[i].FindControl("CheckBox2");

        if (chk1.Checked && chk2.Checked)
        {
           // Do Stuff
        }
    }
}

If you want to verify all checkboxes are checkes in all rows, do this:

protected void Button3_Click(object sender, EventArgs e)
{
    // Declare a boolean flag
    bool AllCheckBoxesAreChecked = true;

    for (int i = 0; i < DetailsView2.Rows.Count; i++)
    {
        CheckBox chk1 = (CheckBox)DetailsView2.Rows[i].FindControl("CheckBox1");
        CheckBox chk2 = (CheckBox)DetailsView2.Rows[i].FindControl("CheckBox2");

        if (!chk1.Checked || !chk2.Checked)
            AllCheckBoxesAreChecked = false;
    }

    // Now use the flag
    if (AllCheckBoxesAreChecked)
    {
        // Do Stuff
    }
}