Gridview checkbox主要来同时删除多条记录
一、在GridView中创建CheckBox
很简单,在前台代码中应用TemplateField。另外一种方法是应用Literal。TemplateField的代码如下:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked="False"
AutoPostBack="True" Text="选择" />asp:CheckBox></ItemTemplate>
<ItemStyle Width="20px"/>
</asp:TemplateField>
二、CheckBox全选、全消
在Gridview1外 再添加一个CheckBox实现全选、全消。由于采用的.net代码实现,要记得把checkSelectAll的AutoPostBack属性设为True。
<asp:CheckBox ID="CheckBox2" runat="server" Text="全选"
onCheckedChanged="CheckBox2_CheckedChanged" AutoPostBack="True" />
后台代码如下:
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox mybox1 = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (CheckBox2.Checked == true)
mybox1.Checked = true;
else
mybox1.Checked = false;
}
}
再加入删除操作,实现多选删除。加个删除按钮:
<asp:Button ID="Button1" runat="server" Text="删除" onclick="Button1_Click "confirm('确定要删除文档吗?')" Width="62px" />
删除代码:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection myconnection = new SqlConnection(con);
myconnection.Open();
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{ CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (cbox.Checked == true)
{ string a = GridView1.DataKeys[i].Value.ToString();
string sqlstr = "delete from Employee where EmployeeID='" + a + "'";
SqlCommand mycommand = new SqlCommand(sqlstr, myconnection);
mycommand.ExecuteNonQuery();
}
}
Gridview1.DataBind();
}
我初学不久,内容比较简单,希望一起学习交流。