Checkbox in TemplateField in Gridview loses checked on postback

Jhorra picture Jhorra · Oct 16, 2009 · Viewed 28.1k times · Source

I have a gridview with a template field. In that template field is a checkbox. I have a submit button outside of the gridview to assign the records that were checked. On the postback no checkboxes register as being checked. Here is my Code:

<Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="cb" Checked="false" runat="server" />
                        <asp:Label ID="lblCFID" runat="server" Visible="false" Text='<%# Eval("ID") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField HeaderStyle-HorizontalAlign="Center" DataField="Name" HeaderText="Name" />
                <asp:BoundField HeaderStyle-HorizontalAlign="Center" DataField="DOB" HeaderText="Date of Birth" />
                <asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Gender" DataField="Gender"  />
                <asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Status" DataField="Status"  />
                <asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Plan Name" DataField="PlanName"  />
                <asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Type" DataField="ControlType"  />
                <asp:BoundField HeaderStyle-HorizontalAlign="Center" HeaderText="Date of Service" dataformatstring="{0:MMMM d, yyyy}" htmlencode="false" DataField="DateofService"  />
            </Columns>

protected void AssignRecords(object sender, EventArgs e)
{
    int Rows = gvASH.Rows.Count;
    for (int i = 0; i < Rows; i++)
    {
        //CheckBoxField cb = ((CheckBoxField)gvASH.Rows[i].Cells[1]).;
        CheckBox cb = (CheckBox)gvASH.Rows[i].Cells[0].FindControl("cb");
        Label lblID = (Label)gvASH.Rows[i].Cells[0].FindControl("lblCFID");
        if (cb.Checked == true)
        {

            string ID = lblID.Text;
            //Assign Code
        }
    }
}

I have a breakpoint set on the string ID = lblID.Text; but it never finds any that are checked.

Answer

Muhammad Akhtar picture Muhammad Akhtar · Oct 16, 2009

I think what you are missing is, when you click on the button and your page is postback, you rebinding to gridview, you need to bind in this condition like

 if (!Page.IsPostBack)
    {
        GridView1.DataSourceID = "yourDatasourceID";
        GridView1.DataBind();
    }