Always getting checkbox as false in grid
asp.net, checkbox, gridview
Solution
I assume that you're always databinding your GridView and not only `if(!Page.IsPostBack)...`.
So put this in `page_load`
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataBindControls(); // like GridView etc.
}
}
If you `DataBind` controls they will lose their changes and ViewState. Even events aren't triggered then. So you should do that only on the first load if `EnableViewState="true"`.
Problem
i have checkboxes in a grid. I am trying to access them from codebehind and get the data for checked /unchecked rows.But even after the checkboxes being checked I am getting them as Checked property as false only: Aspx: ``` <table width="100%"> <asp:GridView ID="grdRequestsPending" runat="server" Width="100%" AutoGenerateColumns="false" BorderWidth="1px" BorderStyle="Solid" Style="margin-left: 0px" BorderColor="#ffcc00" RowStyle-BorderColor="#ffcc00" RowStyle-BorderStyle="Solid" RowStyle-BorderWidth="1px" GridLines="Both" DataKeyNames="ReqID,ApproverComments" On="grdRequestsPending_ItemDataBound" OnRowDataBound="grdRequestsPending_RowDataBound" OnPreRender="grdRequestsPending_PreRender"> <RowStyle CssClass="dbGrid_Table_row" /> <HeaderStyle CssClass="dbGrid_Table_Header" /> <Columns> <asp:TemplateField> <HeaderTemplate> <asp:Label ID="lblSelect" Text="Select All" runat="server"></asp:Label><br /> <asp:CheckBox ID="SelectAll" onclick="javascript:checkAllBoxes(this);" TextAlign="Left" runat="server" /> </HeaderTemplate> <ItemStyle Width="2%" /> <ItemTemplate> <asp:CheckBox ID="chkReq" runat="server"/> </ItemTemplate> <ItemStyle HorizontalAlign="Center" Width="7%" /> </asp:TemplateField> </Columns> ``` But when I am checking these I am always getting them as false in code behind: ``` protected void UpdateVMRequestStatusByCapSupLead(int StatusId) { try { DataTable dt = new DataTable(); dt.Columns.Add("ReqId", typeof(int)); dt.Columns.Add("StatusId", typeof(int)); dt.Columns.Add("ModifiedBy", typeof(string)); dt.Columns.Add("ModifiedDate", typeof(string)); dt.Columns.Add("txtCommentSupLead", typeof(string)); foreach (GridViewRow gr in grdRequestsPending.Rows) { CheckBox chk = (CheckBox)gr.FindControl("chkReq"); if (chk.Checked) { strReqId = strReqId + grdRequestsPending.DataKeys[gr.RowIndex].Value.ToString() + ','; TextBox txtCommentSupLead = (TextBox)gr.FindControl("txtCommentSupLead"); dt.Rows.Add(dt.NewRow()); dt.Rows[dt.Rows.Count - 1]["ReqId"] = Convert.ToInt32(grdRequestsPending.DataKeys[gr.RowIndex].Value); dt.Rows[dt.Rows.Count - 1]["StatusId"] = StatusId; dt.Rows[dt.Rows.Count - 1]["ModifiedBy"] = Session["UserAccentureID"].ToString(); dt.Rows[dt.Rows.Count - 1]["txtCommentSupLead"] = txtCommentSupLead.Text; dt.Rows[dt.Rows.Count - 1].AcceptChanges(); dt.Rows[dt.Rows.Count - 1].SetModified(); } } ``` I am not getting the problem.I am gettign the control also correctly..