Rainhider
Rainhider

Reputation: 836

Gridview checkbox is checked=false even when its been checked?

I have a gridview that is populated with a datatable and has an item template with a checkbox in it. Even when the checkbox is checked, the cs code says checked=false.

Asp:

     <asp:GridView ID="gvListOfPages" runat="server" AutoGenerateColumns="false" ShowHeader="false">
                        <Columns>  
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkPages" runat="server" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="PageName" />                           
                        </Columns>
                    </asp:GridView>

C#:

 foreach (GridViewRow row in gvListOfPages.Rows)
    {
        System.Web.UI.WebControls.CheckBox chk = (System.Web.UI.WebControls.CheckBox)row.Cells[0].FindControl("chkPages");
        if (chk != null && chk.Checked)
        {
            int arrayIndex = Convert.ToInt32(chk.ID.Substring(chk.ID.Length - 1, chk.ID.Length));
        }
    }

Upvotes: 1

Views: 1455

Answers (1)

codeandcloud
codeandcloud

Reputation: 55298

Just change

(System.Web.UI.WebControls.CheckBox)row.Cells[0].FindControl("chkPages")

to

(System.Web.UI.WebControls.CheckBox)row.FindControl("chkPages")

There is no need to specify cell when you are using FindControl. You might be probably hitting chk != null condition.
And if that's not the case then make sure that you are binding your GridView at Page_Load inside !IsPostBack like this.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //Bind your grid here
    }
}

Hope this helps.

Upvotes: 1

Related Questions