当前位置: 代码迷 >> ASP.NET >> DataList组合CheckBox实现多项删除
  详细解决方案

DataList组合CheckBox实现多项删除

热度:4503   发布时间:2013-02-25 00:00:00.0
DataList结合CheckBox实现多项删除
[code=C#][/code]  
  protected void btn_de2_Click(object sender, EventArgs e)
  {
  CheckBox isDeleted;
  foreach (DataListItem anItem in dl1.Items)//遍历所有checkbox找出用户选择的项
  {
  isDeleted = ((CheckBox)anItem.FindControl("Delete"));
  if (isDeleted.Checked)
  {
  string bianh = Convert.ToString(dl1.DataKeys[dl1.SelectedIndex]);//索引超出范围。必须为非负值并小于集合大小。参数名: index
  string bianh = Convert.ToString(dl1.DataKeys[dl1.SelectedItem.ItemIndex]);//未将对象引用设置到对象的实例
  pbClass.Delete(bianh);
  dl1.DataSource = pbClass.DbSource();
  dl1.DataBind();
   
使用了上面两个方法,后面是错误信息,
作了修改后 
string bianh = Convert.ToString(dl1.DataKeys[anItem.ItemIndex]);//集合已修改;可能无法执行枚举操作。

提示了这样的问题,请高手解释一下这些错误的原因,和解决方法。。。。

------解决方案--------------------------------------------------------
没有问题
测试代码
HTML code
<%@ Page Language="C#" EnableViewState="true" %><%@ Import Namespace="System.Xml" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server">  public System.Data.DataTable CreateDataTable()  {    System.Data.DataTable dataTable1 = new System.Data.DataTable("BlogUser");    System.Data.DataRow dr;    dataTable1.Columns.Add(new System.Data.DataColumn("Id", typeof(System.Int32)));    dataTable1.Columns.Add(new System.Data.DataColumn("Title", typeof(System.String)));    for (int i = 0; i < 8; i++)    {      dr = dataTable1.NewRow();      dr[0] = i;      dr[1] = "【孟子E章】" + i.ToString();      dataTable1.Rows.Add(dr);    }    return dataTable1;  }  protected void Page_Load(object sender, EventArgs e)  {    if (!Page.IsPostBack)    {      DataList1.DataSource = CreateDataTable();      DataList1.DataBind();    }  }  protected void Button1_Click(object sender, EventArgs e)  {    CheckBox isDeleted;    foreach (DataListItem anItem in DataList1.Items)//遍历所有checkbox找出用户选择的项    {      isDeleted = ((CheckBox)anItem.FindControl("Delete"));      if (isDeleted.Checked)      {        string bianh = DataList1.DataKeys[anItem.ItemIndex].ToString();        Response.Write("<li>" + bianh);      }    }  }</script><html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server">  <title>无标题页</title></head><body onclick="myfunction()">  <form id="form1" runat="server">  <asp:DataList ID="DataList1" runat="server" DataKeyField="Id">    <ItemTemplate>      <div>        <asp:CheckBox ID="Delete" runat="server" />        <%#Eval("Title") %></div>    </ItemTemplate>  </asp:DataList>  <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Style="height: 21px"    Text="Button" />  </form></body></html>
  相关解决方案