asp.net中怎么选中gridview中的checkbox删除多行

2024-12-25 11:48:09
推荐回答(1个)
回答1:

删除一行和删除多行其实是一样的for (int i = 0; i < this.GridView1.Rows.Count; i++)
你既然循环了GridView1的每一行,也获得的每一行的CheckBoxthis.GridView1.Rows[i].Cells[0].FindControl("CheckBox1") as CheckBox 那么删除多行也就是调用多次using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["sqlStr"].ConnectionString))
{
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "delete from users where id=@id";
comm.Parameters.Add(new SqlParameter("@id", id));
comm.ExecuteNonQuery();
}这段代码建议提出来,单独写成一个方法,这样程序的可读性会更好 protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < this.GridView1.Rows.Count; i++)
{
int id = Convert.ToInt32(this.GridView1.DataKeys[i].Value);
if ((this.GridView1.Rows[i].Cells[0].FindControl("CheckBox1") as CheckBox).Checked == true)
{ Delete(id);
}
}
Bind();
}
private void Delete(int id)
{
using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["sqlStr"].ConnectionString))
{
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "delete from users where id=@id";
comm.Parameters.Add(new SqlParameter("@id", id));
comm.ExecuteNonQuery();
} }