在gridview上多次选择和删除

时间:2013-12-26 10:37:43

标签: asp.net gridview

当我勾选复选框时,它能够循环并获取用户名和产品名称,但为什么不能让我删除?

 foreach (GridViewRow row in GridView1.Rows)
        {
            var check = row.FindControl("chkdelete") as CheckBox;
            if (check.Checked)
            {
                string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                SqlConnection con = new SqlConnection(connStr);
                var uid = row.FindControl("lbluserid") as Label;
                var pid = row.FindControl("lblproductname") as Label;
                SqlCommand cmd = new SqlCommand("delete from ProductReview where userID=@id and productid=@pid", con);
                cmd.Parameters.AddWithValue("@id", uid.Text);
                cmd.Parameters.AddWithValue("@pid", pid.Text);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }

        }

1 个答案:

答案 0 :(得分:0)

  

你能尝试这样的事吗。

    foreach (GridViewRow row in GridView1.Rows)
 {
            var check = row.FindControl("chkdelete") as CheckBox;
            if (check.Checked)
            {              
                var uid = row.FindControl("lbluserid") as Label;
                var pid = row.FindControl("lblproductname") as Label;

                 DatabaseHelperClass.DoDatabaseOperation(uid.Text.Trim(), pid.Text.Trim());

            }

}


Class DatabaseHelperClass
{
   Public static void DoDatabaseOperation(string uid , string pid)
    { string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
      SqlConnection con = new SqlConnection(connStr);
      SqlCommand cmd = new SqlCommand("delete from ProductReview where userID=@id and productid=@pid", con);
      cmd.Parameters.AddWithValue("@id", uid);
      cmd.Parameters.AddWithValue("@pid", pid);
      con.Open();
      cmd.ExecuteNonQuery();
      con.Close();

    }
}