Search code examples
c#winformscheckboxsubsetchecked

How to retrieve a list of checkboxes selected among all those of the form?


I have about 20 checkbox's on the GUI I'm working on and depending on which ones are checked, determines the inputs I need.

I know how to check if a checkbox is checked or not, and can determine the inputs that way.

But I don't want to do that for all 20+ checkbox's.

Is there a way to get the checked checkboxes?

Something like:

string[] ports = new string[3];
ports[] = list_of_checkboxs_that_are_checked;

And then just limit the user to only selecting 3, or however many?


Solution

  • You can loop over them and iterate on the controls on the form.

       foreach(Control c in this.Controls)
       {
          if(c is CheckBox)
          {
             // Do stuff here/logic
          }
       }
    

    Or do a more LINQ/Lamba-ish type approach of

    var checkList = YourForm.Controls.OfType<CheckBox>().Where(x => x.Checked).ToList();
    
    
    checkList.ForEach(x => {
        //Do stuff  here
    });