您的位置:首页 > 编程语言 > ASP

asp.net之DataList里的CheckBox实现全选、反选删除

2014-03-25 17:52 483 查看
前台主要代码:

<asp:DataList ID="DataList1" runat="server">
<HeaderTemplate>
<table style="width:500px" align="center">
<tr>
<td style="width:100px" align="center">
全选
</td>
<td style="width:100px" align="center">
姓名
</td>

<td style="width:100px" align="center">
部门
</td>
<td style="width:100px" align="center">
职位
</td>

</tr>
</table>
</HeaderTemplate>
<ItemTemplate>

<table style="width:500px" align="center">
<tr>

<td style="width:100px" align="center">
<asp:CheckBox ID="chk" runat="server" />
</td>
<td>
<asp:Label ID="lbLoginID" runat="server" Text='<%#Eval("LoginID") %>'></asp:Label>
</td>
<td style="width:100px" align="center">
<asp:Label ID="lbname" runat="server" Text='<%#Eval("UserName") %>'></asp:Label>
</td>

<td style="width:100px" align="center">
<asp:Label ID="lbdepart" runat="server" Text='<%#Eval("Department") %>'></asp:Label>
</td>
<td style="width:100px" align="center">
<asp:Label ID="lbpost" runat="server" Text='<%#Eval("Post") %>'></asp:Label>
</td>

</tr>
</table>
</ItemTemplate>
</asp:DataList>
<asp:CheckBox ID="ChkAll" Text="全选" runat="server" AutoPostBack="True"
oncheckedchanged="ChkAll_CheckedChanged"  />

<asp:Button ID="btn_delete" runat="server" onclick="btn_delete_Click"
Text="删除" OnClientClick="return confirm('您确定做此操作?');" />


后台主要代码:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}

public void bind()
{
string sqlstr = ConfigurationSettings.AppSettings["constr"];
SqlConnection con = new SqlConnection(sqlstr);
string str = "select * from tOAPower";
con.Open();
SqlDataAdapter ada = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
ada.Fill(ds, "tOAPower");
DataList1.DataSource = ds;
DataList1.DataKeyField = "UserID";
DataList1.DataBind();
ds.Dispose();
con.Close();
}
protected void ChkAll_CheckedChanged(object sender, EventArgs e)
{

if (!IsPostBack)
{
ChkAll.Text = "全选";
}
if (ChkAll.Text == "全选")
{
foreach (DataListItem di in this.DataList1.Items)
{
CheckBox ck = (CheckBox)di.FindControl("chk");
ck.Checked = true;
}
this.ChkAll.Text = "全部取消";
}
else
{
foreach (DataListItem di in this.DataList1.Items)
{
CheckBox ck = (CheckBox)di.FindControl("chk");
ck.Checked = false;
}
ChkAll.Text = "全选";
}

}
protected void btn_delete_Click(object sender, EventArgs e)
{

for (int i = 0; i <= DataList1.Items.Count - 1; i++)
{
CheckBox cb = (CheckBox)DataList1.Items[i].FindControl("chk");
if (cb.Checked)
{
string dd = DataList1.DataKeys[i].ToString();

string sqlstr1 = ConfigurationSettings.AppSettings["constr"];
SqlConnection con1 = new SqlConnection(sqlstr1);
con1.Open();
SqlCommand cmd1 = new SqlCommand("delete from tOAPower where UserID='" + dd + "'", con1);

cmd1.ExecuteNonQuery();

cmd1.Dispose();
con1.Close();

}

}
Response.Write("<script>alert('删除成功!');</script>");
bind();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: