Gridview 复选框即使被选中也被选中=false?

Gridview checkbox is checked=false even when its been checked?

我有一个 gridview,其中填充了一个数据表,并且有一个带有复选框的项目模板。即使选中复选框,cs 代码也会显示 checked=false。

Asp:

     <asp:GridView ID="gvListOfPages" runat="server" AutoGenerateColumns="false" ShowHeader="false">
                        <Columns>  
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkPages" runat="server" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="PageName" />                           
                        </Columns>
                    </asp:GridView>

C#:

 foreach (GridViewRow row in gvListOfPages.Rows)
    {
        System.Web.UI.WebControls.CheckBox chk = (System.Web.UI.WebControls.CheckBox)row.Cells[0].FindControl("chkPages");
        if (chk != null && chk.Checked)
        {
            int arrayIndex = Convert.ToInt32(chk.ID.Substring(chk.ID.Length - 1, chk.ID.Length));
        }
    }

只需更改

(System.Web.UI.WebControls.CheckBox)row.Cells[0].FindControl("chkPages")

(System.Web.UI.WebControls.CheckBox)row.FindControl("chkPages")

使用FindControl时无需指定单元格。您可能会达到 chk != null 条件。
如果不是这种情况,请确保您像这样在 !IsPostBack 内的 Page_Load 绑定 GridView

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //Bind your grid here
    }
}

希望对您有所帮助。