Checkbox in TemplateField in Gridview loses checke

2019-02-16 15:11发布

问题:

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.

回答1:

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();
    }


回答2:

On a postback, the contents of the GridView are re-created from the postback Viewstate data between page_init and page_load. Perhaps try examining your Gridview in page_load to see what's there.



回答3:

set the autopostback attribute of Checkbox

AutoPostBack="true"