【问题标题】:How to check/uncheck dynamically created checkboxes in ASP.net如何在 ASP.net 中选中/取消选中动态创建的复选框
【发布时间】:2014-08-27 15:39:30
【问题描述】:

我有这个代码:

 public void CreateCheckBox(int i)
 {
      foreach (ListItem item in listItems.Items)
      {
          CheckBox box = new CheckBox();

          box.Enabled = true;
          box.AutoPostBack = true;
          box.EnableViewState = true;
          box.ID = string.Format("Active_{0}", item.Value);
          box.Text = "Active";
          box.CssClass = "checkbox_format2";

          if (chkSetAllActive.Checked)
          {
              box.Checked = true;
              box.CheckedChanged += new EventHandler(CheckedChange);
          }
          else
          {
             box.Checked = false;
             box.CheckedChanged += new EventHandler(CheckedChange);
          }
          PlaceHolder1.Controls.Add(box);
}

protected void CheckedChange(object sender, EventArgs e)
{
        CheckBox x = (CheckBox)sender;
        if (chkSetAllActive.Checked)
            x.Checked = true;
        else
            x.Checked = false; 
}

PageLoad() 我称之为

CreateCheckBox(listItems.Items.Count);

我还有另一个复选框 (chkSetAllActive)。

问题: 当我点击这个复选框(chkSetAllActive.Checked = true)时,所有动态创建的复选框(活动)都被选中,但是当我想取消选中所有(chkSetAllActive.Checked = false)时,这个动态创建的复选框保持选中状态。我猜动态创建的控件存在一些问题。

如果有人有什么想法,我将不胜感激。

这里还有照片样本:

【问题讨论】:

  • 为复选框chkSetAllActive设置autoPostBacktrue

标签: c# asp.net checkbox


【解决方案1】:

首先,从CreateCheckBox 中删除box.Checked = ... 代码。它不属于那里。即使chkSetAllActive-CheckBox 没有被点击,你也会修改回发的Checked-state。

你应该这样处理chkSetAllActiveCheckedChanged事件:

var allChk = PlaceHolder1.Controls.OfType<CheckBox>()
    .Where(chk => chk.Text == "Active"); // to avoid problems
foreach(CheckBox chk in allChk)
    chk.Checked = chkSetAllActive.Checked;

编辑:非 LINQ

foreach(Control ctrl in PlaceHolder1.Controls)
{
    CheckBox chk = ctrl as CheckBox;
    if(chk != null && chk.Text == "Active")
        chk.Checked = chkSetAllActive.Checked;
}

【讨论】:

  • .OfType() 它不会识别这部分
  • @MeMememe:你要加using System.Linq;
  • 感谢您的回答,但很遗憾我无法使用 LINQ。我正在使用 .NET 2.0(我想我应该先提一下,抱歉)如果您有其他解决方案,我将不胜感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 2016-11-25
  • 2019-05-25
相关资源
最近更新 更多