CheckBox与DataGrid混用&DataSet批量删除数据

前段时间因为急用所以查资料做了一个CheckBox与DataGrid混用,且用DataSet批量删除数据的例子,今天用WebMatrix写了一个非常简单的,希望能对初学者起到一个抛砖引玉的作用(因WebMatrix默认不是代码分离,请不要用VS.net打开)

图片

此主题相关图片如下:



代码:

<%@ Page Language="C#" Debug="true" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.OleDb" %>
<script runat="server">

OleDbConnection myConn;
string strSql;
OleDbDataAdapter myComm;
DataSet ds;
OleDbCommandBuilder nameCmdBd;

public void Page_Load(object sender,EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}

public void chkAll_changed(object sender,EventArgs e)
{
CheckBox cb=(CheckBox)sender;
foreach(DataGridItem i in dgrdName.Items)
{
CheckBox cb1=(CheckBox)i.FindControl("chkDel");
if(cb.Checked)
cb1.Checked=true;
else
cb1.Checked=false;
}
}

void Item_Del(object sender, EventArgs e)
{
myConn=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath("data.mdb"));
strSql="select * from users";
myComm=new OleDbDataAdapter(strSql,myConn);
ds=new DataSet();
myComm.Fill(ds,"name");
for(int i=0;i<dgrdName.Items.Count;i++)
{
CheckBox cb=(CheckBox)dgrdName.Items[i].FindControl("chkDel");
if(cb.Checked)
{
ds.Tables["name"].Rows[i].Delete();
}
}
nameCmdBd=new OleDbCommandBuilder(myComm);
myComm.Update(ds,"name");
dgrdName.DataSource=ds.Tables["name"].DefaultView;
dgrdName.DataBind();
}

void BindGrid()
{
myConn=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath("data.mdb"));
strSql="select * from users";
myComm=new OleDbDataAdapter(strSql,myConn);
ds=new DataSet();
myComm.Fill(ds,"user");
dgrdName.DataSource=ds.Tables["user"].DefaultView;
dgrdName.DataBind();
}

</script>
<html>
<head>
</head>
<body style="FONT-SIZE: 9pt; FONT-FAMILY: verdana">
<form runat="server">
<p>
<asp:DataGrid id="dgrdName" runat="server" BorderStyle="None" BorderWidth="1px" BorderColor="#CC9966" BackColor="White" CellPadding="4" Font-Size="9pt" Font-Names="verdana" AutoGenerateColumns="False">
<FooterStyle forecolor="#330099" backcolor="#FFFFCC"></FooterStyle>
<HeaderStyle font-bold="True" forecolor="#FFFFCC" backcolor="#990000"></HeaderStyle>
<PagerStyle horizontalalign="Center" forecolor="#330099" backcolor="#FFFFCC"></PagerStyle>
<SelectedItemStyle font-bold="True" forecolor="#663399" backcolor="#FFCC66"></SelectedItemStyle>
<ItemStyle forecolor="#330099"></ItemStyle>
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" OnCheckedChanged="chkAll_changed" Runat="server" AutoPostBack="True"></asp:CheckBox>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkDel" Runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="id" HeaderText="编号"></asp:BoundColumn>
<asp:BoundColumn DataField="name" HeaderText="姓名"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
</p>
<p>
<asp:Button id="Button1" onclick="Item_Del" runat="server" Text="删除所选条目"></asp:Button>
</p>
</form>
</body>
</html>

你可能感兴趣的:(checkbox)