moe
moe

Reputation: 5249

How can I set checkboxlist items as checked by default

In my page i have a CheckBoxList control and i would like all the checkboxes to be checked by default. how can i do that? i have tried couple ways but it is not doing it. here is my code behind:

protected void chkAll_CheckedChanged(object sender, EventArgs e)
    {

        foreach(GridViewRow gr in GridView1.Rows)
        {

            CheckBox cb = (CheckBox)gr.FindControl("chkItem");
            cb.Checked = true;
            if(((CheckBox)sender).Checked)
             cb.Checked = true;
                else
             cb.Checked = false;
        }

    }

and here is my ASPX code:

<asp:TemplateField HeaderText="Check All">
                    <HeaderTemplate>
                        <asp:CheckBox ID="chkAll" runat="server" AutoPostBack="True" OnCheckedChanged="chkAll_CheckedChanged" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="chkItem" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>

Upvotes: 0

Views: 4251

Answers (1)

Pal R
Pal R

Reputation: 534

Use the following ASPX:

<asp:GridView runat="server" ID="m_gridView" AutoGenerateColumns="False">
                <Columns>
                    <asp:TemplateField HeaderText="Check All">
                        <HeaderTemplate>
                            <asp:CheckBox ID="chkAll" runat="server" AutoPostBack="True" OnCheckedChanged="chkAll_CheckedChanged" Checked="True" />
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:CheckBox ID="chkItem" runat="server" Checked="True" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

It should have Check All and the individual check boxes checked by default.

In you code behind do the following:

protected void chkAll_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox l_cbAll = (CheckBox)m_gridView.HeaderRow.FindControl("chkAll");
        foreach (GridViewRow l_row in m_gridView.Rows)
        {
                CheckBox l_cb = (CheckBox)l_row.FindControl("chkItem");
                l_cb.Checked = l_cbAll.Checked;
        }
    }

Upvotes: 1

Related Questions