Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how loop through multiple checkbox in C#

I have 100 checkboxes in a winform. Their names are sequential like checkbox1, checkbox2 etc. I have a submit button in my winform. After clicking the submitting button, it checks, if a checkbox is checked then some value is updated otherwise another value is updated. I have to check 100 checkbox. So i have to loop through the 100 checkbox to check if the checkbox is checked or not.

I know how to check the checkbox

private void sumit_button_Click(object sender, EventArgs e)
{
     if (checkbox1.Checked)
     { 
        //  update 
     }
     else
     {  
        // update another  
     }

     if (checkbox2.Checked)
     {  
        //  update    
     }
     else
     {   
        // update another  
     }

     ......................and so on

} 
        

But how can i do this for 100 checkbox???

like image 766
ImonBayazid Avatar asked Dec 01 '22 18:12

ImonBayazid


2 Answers

foreach (var control in this.Controls) // I guess this is your form
            {
                if (control is CheckBox)
                {
                    if (((CheckBox)control).Checked)
                    {
                        //update
                    }
                    else
                    {
                        //update another
                    }
                }
            }
like image 63
heq Avatar answered Dec 04 '22 08:12

heq


foreach (var ctrl in panel.Controls) {
    if (ctrl is CheckBox && ((CheckBox)ctrl).IsChecked) {
        //Do Something
    }
}
like image 21
coder Avatar answered Dec 04 '22 09:12

coder