【问题标题】:selecting individual rows from gridview using check box使用复选框从 gridview 中选择单个行
【发布时间】:2013-09-03 09:41:37
【问题描述】:

我有一个 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();

            }

                            }

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

【问题讨论】:

  • 你是把ID绑定到第二列还是第一列?你的代码看起来不错!难道你需要GridView1.Rows[i].Cells[0].Text
  • 嗨,afzalulh,我试过了,它说找不到 ID。我想这是因为复选框在第 0 行?
  • 什么是view();?你是通过这个重新绑定 Gridview 吗?
  • 是的。这是一个函数。
  • 这就是问题所在。重新绑定后重新生成所有行。因此,在完成检查和更新数据库后绑定 GridView。请在下面查看我的答案。

标签: asp.net gridview checkbox


【解决方案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) 
        {
            //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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-23
    • 2021-04-11
    • 2014-06-29
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多