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

删除一行的代码如下:protectedvoidButton1_Click(objectsender,EventArgse){for(inti=0;i<this.GridV... 删除一行的代码如下: 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)
{
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();
}
Bind();
}
}
}
展开
 我来答
匿名用户
推荐于2018-04-13
展开全部
删除一行和删除多行其实是一样的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();
} }
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式