日期:2014-05-17  浏览次数:20509 次

repeater里checkbox值问题
repeater用checkbox全选,repeater外的LinkButton执行删除,代码如下:[code=C#][/code] /// <summary>
  ///批量删除
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  protected void lbtnDel_Click(object sender, EventArgs e)
  {
  for (int i = 0; i < this.rptList.Items.Count; i++)
  {
  CheckBox cb = (CheckBox)rptList.Items[i].FindControl("cb_id");
  int id = Convert.ToInt32(((Label)rptList.Items[i].FindControl("lb_id")).Text);

  if (cb.Checked)
  {

  string str = "delete from T_News where Nid=" + id;
  DbHelper.NoResultCommand(str);
  }

  else
  {
  Response.Write("没有选中文本");
  }
  }
  PageCountBind(1, drNewsCatList.SelectedValue);
  }
执行删除事件之后,发现删除不了,直接进else语句
调试发现:checkbox的值一直是false,i,id可以循环到值
进一步调试发现,当执行删除事件之前都要先执行pageload里的事件,但是pageload里面已经!IsPostBack了

求指教

------解决方案--------------------
初步估计 你在执行删除事件时又重新将repeater 初始化了,那样checkbox 很可能复原了
------解决方案--------------------
是你代码没写好,js也是可以的

HTML code
<%@ Page Language="C#" EnableViewState="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  protected void Page_Load(object sender, EventArgs e)
  {
    xx.InputAttributes.Add("onclick", "SelectAll(this)");
    System.Data.DataTable dt = new System.Data.DataTable();
    if (!Page.IsPostBack)
    {
      System.Data.DataRow dr;
      dt.Columns.Add(new System.Data.DataColumn("Id", typeof(System.Int32)));
      dt.Columns.Add(new System.Data.DataColumn("Name", typeof(System.String)));
      for (int i = 0; i < 6; i++)
      {
        dr = dt.NewRow();
        dr[0] = i;
        dr[1] = "【孟子E章】" + i.ToString();
        dt.Rows.Add(dr);
      }
      rptList.DataSource = dt;
      rptList.DataBind();
    }
  }

  protected void LinkButton1_Click(object sender, EventArgs e)
  {
    bool hasChecked = false;
    for (int i = 0; i < this.rptList.Items.Count; i++)
    {
      CheckBox cb = (CheckBox)rptList.Items[i].FindControl("cb_id");
      int id = Convert.ToInt32(((Label)rptList.Items[i].FindControl("lb_id")).Text);
      if (cb.Checked)
      {
        Response.Write("<li> delete from T_News where Nid=" + id);
        hasChecked = true;
        //DbHelper.NoResultCommand(str);
      }
    }
    if (!hasChecked)
    {
      Response.Write("没有选中文本");
    }
    else
    {
      //Response.Redirect(Request.UrlReferrer.ToString());
    }
  }
</script>
<script type="text/javascript">
  function SelectAll(chkBox) {
    s = document.getElementsByTagName("input");
    for (i = 0; i < s.length; i++) {
      if (s[i].type == "checkbox" && s[i].id && s[i].id.indexOf("cb_id") > -1) {
        s[i].checked = chkBox.checked;
      }
    }
  }
</script>
<body>
  <form id="form1" runat="server">
  <asp:Repeater ID="rptList" runat="server">
    <ItemTemplate>
      <div>
        <asp:CheckBox ID="cb_id" runat="server" /><asp:Label ID="lb_id" runat="server" Text='<%#Eval("Id") %>'></asp:Label>