Share via


loop through checkboxes and uncheck them

Question

Wednesday, April 4, 2012 11:55 PM | 1 vote

I have some checkboxes on a form and would like to be able to loop through them and uncheck them if they are checked.  This is what I have so far:

foreach (Control c in this.Controls)
{
   if (c is CheckBox && c != null)
   // need code
}

All replies (4)

Thursday, April 5, 2012 12:49 AM ✅Answered

foreach (Control c in this.Controls)
{
 if (c is CheckBox && c != null)
 {
   // need code
  ((CheckBox)c).Checked = false;
 }
}

It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.


Thursday, April 5, 2012 9:45 AM ✅Answered | 1 vote

I would use something like

foreach(CheckBox c in this.Controls.OfType<CheckBox>()){    c.Checked = false;}

Thursday, April 5, 2012 12:57 AM

((CheckBox)c).Checked = false;

Thursday, April 5, 2012 6:19 PM

I like Louis.fr's version way better.  OfType thins out the set of things that you have to look at and the risk of getting something of the wrong type is greatly reduced.  There's no casting code, so it's way better, in my opinion.