Me Mememe
Me Mememe

Reputation: 5

How to check/uncheck dynamically created checkboxes in ASP.net

I have this code:

 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; 
}

and in PageLoad() I call this

CreateCheckBox(listItems.Items.Count);

Also I have another checkBox (chkSetAllActive).

Problem: When I click this checkbox (chkSetAllActive.Checked = true) all dynamically created checkboxes (Active) are being checked but when I want to uncheck all (chkSetAllActive.Checked = false) this dynamically created checkboxes stays checked. I guess there is some problem with dynamically created controls.

If anyone have some ideas I would be thankful.

here is also photo sample:

enter image description here

Upvotes: 0

Views: 5075

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460048

First, remove the box.Checked = ... code from CreateCheckBox. It does not belong there. You will modify the Checked-state on postbacks even if the chkSetAllActive-CheckBox wasn't clicked.

You should handle the CheckedChanged event of the chkSetAllActive in this way:

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

Edit: non-LINQ

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

Upvotes: 2

Related Questions