利用checkbox 删除gridview里的数据

来源:互联网 发布:linux删除用户组的命令 编辑:程序博客网 时间:2024/06/05 09:46
<asp:GridView id="GridView1" runat="server" DataKeyNames="id" AllowSorting="True" AutoGenerateColumns="False" OnRowDeleting="GridView1_RowDeleting" SkinID="gvSkin" Width="100%" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemStyle HorizontalAlign="Center" Width="3%" />
<ItemTemplate>
<asp:CheckBox ID="ckbDelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="NameNews" HeaderText="新闻标题" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="TypeNews" HeaderText="新闻类型">
<ItemStyle HorizontalAlign="Center" Width="10%" />
</asp:BoundField>
<asp:BoundField DataField="PeopleNews" HeaderText="发布人">
<ItemStyle HorizontalAlign="Center" Width="10%" />
</asp:BoundField>
<asp:BoundField DataField="DateNews" DataFormatString="{0:yyyy-MM-dd}" HeaderText="添加日期"
HtmlEncode="False">
<ItemStyle HorizontalAlign="Center" Width="10%" />
</asp:BoundField>
<asp:BoundField DataField="ButtonNews" HeaderText="点击数">
<ItemStyle HorizontalAlign="Center" Width="10%" />
</asp:BoundField>
<asp:HyperLinkField DataNavigateUrlFields="id" DataNavigateUrlFormatString="News_Modfiy.aspx?id={0}"
HeaderText="操作" Text="修改" >
<ItemStyle HorizontalAlign="Center" Width="6%" />
</asp:HyperLinkField>
<asp:CommandField HeaderText="操作" ShowDeleteButton="True" DeleteText="<div id="de" onclick="JavaScript:return confirm('确定删除吗?')">删除</div>" >
<ItemStyle HorizontalAlign="Center" Width="6%" />
</asp:CommandField>
</Columns>
</asp:GridView>
<asp:CheckBox id="CheckBox1" runat="server" Text=" 选中/取消所有" AutoPostBack="True" OnCheckedChanged="CheckBox1_CheckedChanged"></asp:CheckBox> <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="删除选中项" OnClientClick='return confirm("你确定要删除?")'></asp:Button>

=================================.cs代码

protected void Button1_Click(object sender, EventArgs e)
{
for (int rowindex = 0; rowindex < this.GridView1.Rows.Count; rowindex++)
{
if (((CheckBox)this.GridView1.Rows[rowindex].Cells[0].FindControl("ckbDelete")).Checked == true)
{
int intID = Convert.ToInt32(this.GridView1.DataKeys[rowindex].Value);
string strSql = "DELETE FROM OC_Product WHERE id=" + intID;
//对数据库执行删除操作省略
}
}
ShowNews();
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
foreach (GridViewRow row in GridView1.Rows)
{
((CheckBox)row.Cells[0].FindControl("ckbDelete")).Checked = true;
}
}
else
{
foreach (GridViewRow row in GridView1.Rows)
{
((CheckBox)row.Cells[0].FindControl("ckbDelete")).Checked = false;
}
}
}
原创粉丝点击