简体   繁体   English

即使已选中Gridview复选框,其checked = false也可以?

[英]Gridview checkbox is checked=false even when its been checked?

I have a gridview that is populated with a datatable and has an item template with a checkbox in it. 我有一个用数据表填充的gridview,并且有一个带有复选框的项目模板。 Even when the checkbox is checked, the cs code says checked=false. 即使选中该复选框,cs代码也会显示checked = false。

Asp: 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#: 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));
        }
    }

Just change 只是改变

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

to

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

There is no need to specify cell when you are using FindControl . 使用FindControl时无需指定单元格。 You might be probably hitting chk != null condition. 您可能会遇到chk != null条件。
And if that's not the case then make sure that you are binding your GridView at Page_Load inside !IsPostBack like this. 如果不是这种情况,请确保在这样的!IsPostBack内部的Page_Load处绑定GridView

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM