1

我有一个 gridview,其中包含模板字段内的复选框。我想检索选中复选框的行的值,以便我可以通过数据库更新它们。这是我的代码:

    protected void approve_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            if (((CheckBox)GridView1.Rows[i].FindControl("Select")).Checked) 
            {

//我想如果循环找到一个选中的复选框,它将对该行执行以下操作:

                con.Open();

                string approve = "update table set status ='Approved' where ID=" + GridView1.Rows[i].Cells[1].Text + "";

                SqlCommand scmapprove = new SqlCommand(approve, con);

                scmapprove.ExecuteNonQuery();

                view();

                con.Close();

            }

                            }

但是,它似乎不起作用。例如,我从表中检查了五行,它只更新第一行。我应该怎么办?

4

1 回答 1

2

You are rebinding the Gridview after finding a checked row. Bind it after completing all update operations:

protected void approve_Click(object sender, EventArgs e)
{
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        if (((CheckBox)GridView1.Rows[i].FindControl("Select")).Checked) 
        {
            //I thought if the loop finds a checked check box, it will execute the following to that row:
            con.Open();
            string approve = "update table set status ='Approved' where ID=" + GridView1.Rows[i].Cells[1].Text + "";

            SqlCommand scmapprove = new SqlCommand(approve, con);
            scmapprove.ExecuteNonQuery();

            //view(); //Donot rebind the gridview now.
            con.Close();
        }
    }

    view();
}
于 2013-08-30T17:18:29.607 回答