开发者

Checkbox in TemplateField in Gridview loses checked on postback

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>
                    <开发者_JS百科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.


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


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.


set the autopostback attribute of Checkbox

AutoPostBack="true" 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜