0

我有一个包含 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();
}
4

1 回答 1

0

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

如果页面处于回发状态,则不要进行数据绑定,您可以if (!Page.IsPostBack)在调用之前添加一个,LoadExceptions()或者您可以更新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();
    }
}
于 2013-05-27T22:42:22.827 回答