DataList checkBox全选删除

最近需要用到一个全选删除功能。
主要思路这个例子是用一个隐藏的服务器控件 input type
="hiddent"
来绑定每项的唯一建值ID
当然也有其它的办法。网上有用checkbox的value值来绑定ID 但是我试了没管用。
还可以用label来绑定。然后把控件的是否显示属性设为false但是我没做过具体用起来什么情况
也不知道。
看下面的代码由于是在外面上网没有VS 代码全是用记事本写的。可能有误。但是大概思路是错不
了的。
//aspx

        <asp:DataList ID="DataList1" runat="server">
        
<ItemTemplate>
        
<input type="hidden" id="SelectedID" runat="server"   value='<%# DataBinder.Eval(Container.DataItem,"now_id")%>'  NAME="SelectedID"/>
        
<asp:CheckBox ID="CheckBox1" runat="server" /> 
        
        
<%#DataBinder.Eval(Container.DataItem, "now_id")%>

        
<%#DataBinder.Eval(Container.DataItem, "now_name")%>
        
</ItemTemplate>
        
</asp:DataList>
//aspx.cs
#resgion 执行删除(选中项)
    
protected void Button2_Click(object
 sender, EventArgs e)
    
{
        
{
            
string dgIDs = ""
;
            
bool BxsChkd = false
;
            
foreach (DataListItem i in
 DataList1.Items)
            
{
                CheckBox deleteChkBxItem 
= (CheckBox)i.FindControl("CheckBox1"
);
                
if
 (deleteChkBxItem.Checked)
                
{
                    BxsChkd 
= true
;
                    dgIDs 
+= ((HtmlInputHidden)i.FindControl("SelectedID")).Value.ToString() + ","
;
                }

            }

            
string SQL = "DELETE   from   now   WHERE   now_id   IN   (" + dgIDs.Substring(0, dgIDs.LastIndexOf(",")) + ")";

            
if (BxsChkd == true
)
            
{

                
try

                
{
                    SqlConnection conn 
= new SqlConnection("server=ss/sqlexpress;database=test1;uid=sa;pwd=;"
);
                    SqlCommand comm 
= new
 SqlCommand(SQL, conn);

                    conn.Open();
                    comm.ExecuteNonQuery();
                    conn.Close();
                    Response.Redirect(
"@.aspx"
);
                }

                
catch (SqlException err)
                
{
                }

                
//BindData();
            }

        }

    }

#endregion

#regioin
//checkbox全选
        foreach (DataListItem item in this.DataList1.Items)
        
{
            ((CheckBox)item.FindControl(
"CheckBox1")).Checked = this
.CheckBox2.Checked;
        }

//button全选
         foreach (DataListItem item in this.DataList1.Items)
        
{
            ((CheckBox)item.FindControl(
"CheckBox1")).Checked = false
;
        }

#endregion
// 当然你也可以在 Page_Load 中加入这个在删除是询问一下
this.Button1.Attributes.Add("onclick""javascript:return confirm('您确认要删除吗?')");

原文地址:https://www.cnblogs.com/zhangchenliang/p/3060515.html