asp.net下gridview 批量删除的实现方法

功能:选中CheckBox,后从数据库中删除选中项。文章侧重将如何实现批量删除,对于如何链接数据库和绑定数据不做详细解释。
1 我们先要在GridView中添加一列为CheckBox。代码如下:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="vote_id" HeaderText="编号" />
<asp:BoundField DataField="vote_name" HeaderText="名称" />
<asp:TemplateField HeaderText="选择">
<ItemTemplate>
<asp:CheckBox id="cbxId" runat="Server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

 

注意id为cbxId,呆会我们要用到。

 

2./初始化数据
private void dataInit()
{
string sqlText = "select * from vote";
SqlConnection conn = getCon();
SqlDataAdapter da = new SqlDataAdapter(sqlText,conn);
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds, "vote");
GridView1.DataSource = ds;
GridView1.DataKeyNames = new string[]{"vote_id"};
GridView1.DataBind();
conn.Close();
conn.Dispose();
}

 

3 点击“删除选中”按钮的事件。

protected void Button1_Click(object sender, EventArgs e)
{
string sqlText = "(";
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//搜索第n行3列
CheckBox cbx = (CheckBox)GridView1.Rows[i].FindControl("cbxId");
if (cbx.Checked == true)
{
sqlText = sqlText + Convert.ToInt32(GridView1.DataKeys[i].Value) + ",";
}
}
//去掉最后的逗号,并且加上右括号
sqlText = sqlText.Substring(0,sqlText.Length - 1) + ")";
sqlText = "delete vote where vote_id in" + sqlText;
try
{
//执行删除语句
SqlConnection conn = getCon();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlText,conn);
int delCount = Convert.ToInt32(cmd.ExecuteNonQuery());
Response.Write("<script>alert('共删除" + delCount + "条数据');</script>");
dataInit();
}
catch(Exception ex)
{
//若有错误发生,输出错误信息
Response.Write(ex.Message);
}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值