我们在开发网站的时候,有个很常见的功能,就是要让GridView能够选择多项,然后一起删除。效果类似下面这张图,这是我网站后台管理页面中的一个GridView。
其实制作这个效果不难,思路是:增加一个checkbox列,这个列的数据绑定到表的主键(比如Id),前台的代码可以在VS的可视化设计器中完成,你要做的仅仅只是增加一个CheckBox列。
前台代码如下:
<asp:gridview id="GridView2" runat="server" autogeneratecolumns="False" datakeynames="ID" datasourceid="AccessDataSource2" allowpaging="True" allowsorting="True" cellpadding="4" enablemodelvalidation="True" forecolor="#333333">
<alternatingrowstyle backcolor="White" forecolor="#284775">
<columns>
<asp:templatefield headertext="选择">
<itemtemplate>
<asp:checkbox id="CheckBox1" runat="server"></asp:checkbox>
</itemtemplate>
<edititemtemplate>
<asp:checkbox id="CheckBox1" runat="server"></asp:checkbox>
</edititemtemplate>
<itemstyle horizontalalign="Center"></itemstyle>
</asp:templatefield>
<asp:boundfield datafield="ID" headertext="ID">
<asp:boundfield datafield="fdname" headertext="链接名称" sortexpression="fdname">
<headerstyle height="24px">
<itemstyle height="22px"></itemstyle>
</headerstyle>
</asp:boundfield>
<asp:boundfield datafield="fdurl" headertext="链接地址" sortexpression="fdurl">
<asp:boundfield datafield="orderId" headertext="排序ID" sortexpression="orderId">
<asp:commandfield headertext="编辑" showeditbutton="True">
<asp:templatefield headertext="删除" showheader="False">
<itemtemplate>
<asp:linkbutton id="LinkButton1" runat="server" causesvalidation="False" commandname="Delete" text="删除" onclientclick="return confirm(‘真的要删除吗?‘)"></asp:linkbutton>
</itemtemplate>
</asp:templatefield>
</asp:commandfield>
</asp:boundfield>
</asp:boundfield>
</asp:boundfield>
</columns>
<editrowstyle backcolor="#999999">
<footerstyle backcolor="#5D7B9D" font-bold="True" forecolor="White">
<headerstyle backcolor="#5D7B9D" font-bold="True" forecolor="White">
<pagerstyle backcolor="#284775" forecolor="White" horizontalalign="Center">
<rowstyle backcolor="#F7F6F3" forecolor="#333333">
<selectedrowstyle backcolor="#E2DED6" font-bold="True" forecolor="#333333"></selectedrowstyle>
</rowstyle>
</pagerstyle>
</headerstyle>
</footerstyle>
</editrowstyle>
</alternatingrowstyle>
</asp:gridview>
后台代码如下:
protected void Button2_Click(object sender, EventArgs e)
{
//获取要更改的项目
ArrayList checkedList = new ArrayList();
for (int i = 0; i < this.GridView2.Rows.Count; i++)
{
string ID = this.GridView2.Rows[i].Cells[1].Text;
CheckBox cb = this.GridView2.Rows[i].FindControl("CheckBox1") as CheckBox;
if (checkedList.Contains(ID) && !cb.Checked)
{
checkedList.Remove(ID);
}
if (!checkedList.Contains(ID) && cb.Checked)
{
checkedList.Add(ID);
}
}
//逐条更改
int count = 0;
for (int i = 0; i < checkedList.Count; i++)
{
string SQL = "DELETE * FROM Fdlinks where ID=" + checkedList[i].ToString();
int OK = OleDbHelper.ExecNQ(SQL);
if (OK == 1)
{
count++;
}
}
Label2.Text = count + "条记录被更改";
GridView2.DataSourceID = AccessDataSource2.ID;
GridView2.DataBind();
}