在GridView中获取CheckBox值的问题

本文关键字:问题 CheckBox 获取 GridView | 更新日期: 2023-09-27 18:15:31

我有一个包含CheckBox控件的GridView。一旦用户选中了他们想要的行,他们就单击一个按钮,我必须为选中的每一行更新数据库。

我有代码迭代通过gridview行,看看复选框值,但它总是假的,即使它被选中。我确实得到了忽略复选框的引用,但它总是假的。我遗漏了什么?

aspx.cs文件:

protected void Ignore_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in grdNotReceived.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            CheckBox ignore = (CheckBox)row.FindControl("chkIgnore");
            if (ignore.Checked)
            {
                // Update Database
            }
        }
    }
}

。aspx页面:

<asp:GridView ID="grdNotReceived" runat="server"
    Width="600px"
    CssClass="mGrid"
    AlternatingRowStyle-CssClass="alt"
    PagerStyle-CssClass="pgr" AutoGenerateColumns="false">
<AlternatingRowStyle CssClass="alt"/>
<Columns>
    <asp:BoundField DataField="Store" HeaderText="Store" />
    <asp:BoundField DataField="Dept" HeaderText="Dept" />
    <asp:BoundField DataField="Type" HeaderText="Type" />
    <asp:BoundField DataField="RefNumber" HeaderText="RefNumber" />
    <asp:BoundField DataField="Date" HeaderText="Date" />
    <asp:BoundField DataField="Vendor" HeaderText="Vendor" />
    <asp:BoundField DataField="Total" HeaderText="Total" />
    <asp:TemplateField>
        <ItemTemplate>
            <asp:CheckBox ID="chkIgnore" runat="server" Checked="false" />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:CheckBox ID="chkIgnore" runat="server" Checked="false" />
        </EditItemTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

GridView数据绑定方法:

protected void LoadExceptions()
{
    Database db = new Database();
    SqlCommand sql = new SqlCommand();
    sql.CommandText = "getSobeysNotReceived";
    this.grdNotReceived.DataSource = db.GetSprocDR(sql);
    this.grdNotReceived.DataBind();
    db.Close();
}

在GridView中获取CheckBox值的问题

如果您的数据绑定函数(LoadExceptions())在页面加载的某处被调用(如Load事件或类构造函数),那么它将覆盖用户在表单中所做的更改。

如果页面在post back中,请不要绑定,您可以在调用LoadExceptions()之前添加if (!Page.IsPostBack),或者您可以更新LoadExceptions()来检查它:

protected void LoadExceptions()
{
    if (!Page.IsPostBack)
    {
        Database db = new Database();
        SqlCommand sql = new SqlCommand();
        sql.CommandText = "getSobeysNotReceived";
        this.grdNotReceived.DataSource = db.GetSprocDR(sql);
        this.grdNotReceived.DataBind();
        db.Close();
    }
}