我有一个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();
}
}
然而,它似乎不起作用。例如,我检查了表中的五行,它只更新了第一行。我该怎么办?
答案 0 :(得分:2)
您在找到选中的行后重新绑定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)
{
//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();
}