ARATHY
ARATHY

Reputation: 349

For loop on multiple check boxes

I have checkboxes named CheckBox1,CheckBox3,CheckBox5,CheckBox7,CheckBox9,CheckBox11. I wants to iterate through these check boxes and wants to disable them. I have written like this

for (int i=1; i < 12; i++)
{              
    ((CheckBox)(i.ToString())).Enabled = false;
    i=i+2;
}

but this is not the proper way. please help

Upvotes: 1

Views: 1275

Answers (3)

Sachin
Sachin

Reputation: 40990

Try using FindControl like this if you have id of controls like Checkbox1,Checkbox3 etc.

for (int i = 1; i < 12; i+=2)
{
  CheckBox cb = (CheckBox)Page.FindControl("Checkbox" + i);
  cb.Enabled = false;
}

Upvotes: 4

DatRid
DatRid

Reputation: 1169

May this help you.

foreach (Control c in Page.Controls)
{
   if (c is CheckBox)
   {
      CheckBox myCheckBox = (CheckBox)c;
      myCheckBox.Enabled = false;
   }
}

This will disable you all CheckBoxes you have. Edit: Sorry didnt see the +2 at the i. My fault.

Upvotes: 0

tonycoupland
tonycoupland

Reputation: 4247

Your code would like to set the enabled=false for checkboxes that have an odd number at the end of their id? Then this will do that

foreach (Control ctrl in Page.Controls)
{
   if (ctrl is CheckBox && ctrl.id.length > 9)
   {
      int chkboxNumber = int.Parse(ctrl.id.SubStr(9));
      if ( chkboxNumber % 2 == 1) // Check for odd numbers
      {
          (CheckBox)ctrl.Enabled = false; 
      }
   }
}

Upvotes: 0

Related Questions