Search code examples
c#asp.netgridviewcheckboxispostback

CheckBox "Checked" value in GridView is always false


I'm using a checkbox column in a gridview which is populated from a SQL database. A button below the gridview should retrieve the data of the rows whose checkboxe's have been checked. When I loop over all the rows checkboxe's, none of them has checked==true even though I have checked them all before clicking the button. Here is the ASP.NET code:

<asp:TemplateField>
        <ItemTemplate>
            <asp:CheckBox ID="chkRow" runat="server" />
        </ItemTemplate>
</asp:TemplateField>

and here is the button's action that loops over all the rows' checkboxes:

protected void GetSelectedRecords(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridView1.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);               
            if (chkRow != null && chkRow.Checked) //chkRow.Checked is always "false" 
            {
                string name = row.Cells[2].Text;
            }
        }  
     }              
}

Thanks a lot in advance. I'd greatly appreciate any help.


Solution

  • If you are binding your grid in Page_Load, Make sure you are not binding your grid outside of if(!IsPostBack){}. Otherwise you will loose the checkboxe's on each postback and therefore losing the status of checkboxe's.

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
           //Bind Your Grid Here
        }
    }