Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, August 20, 2013 11:08 PM
I have 8 Group Boxes that have checkbox controls on all of them. I am looking for a way to traverse all of the group boxes, and get the status of the checkboxes in these group boxes.
I can find the checkboxes when I do one groupbox at a time shown below, but struggling with multiple group boxes.
foreach(Control g in groupBox2)
{
if (g is CheckBox)
{
listBox1.Items.Add(g.Name.ToString());
}
}
All replies (3)
Thursday, August 22, 2013 6:16 AM ✅Answered
Hi Radgator,
Welcome to MSDN Forum Support.
You need to replace groupBox2 into groupBox2.Controls,otherwise Visual Studio develop environment would rase the Error 1 "foreach statement cannot operate on variables of type 'System.Windows.Forms.GroupBox' because 'System.Windows.Forms.GroupBox' does not contain a public definition for 'GetEnumerator' D:\ProgramInThread\GetCheckBoxControlsDemo\GetCheckBoxControlsDemo\GetCheckBoxControlsDemo\Form1.cs 22 13 GetCheckBoxControlsDemo".
Here is its code snipppet as follows:
foreach (Control g in groupBox2.Controls) { if (g is CheckBox) { listBox1.Items.Add(g.Name.ToString()); } }
Its compressed solution I will upload it to Skydriver at https://skydrive.live.com/?cid=0b0be87e30d620ca#cid=0B0BE87E30D620CA&id=B0BE87E30D620CA%21105. The slution name is GetCheckBoxControlsDemo.zip.
Sincerely,
Jason Wang
<THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
Thanks
MSDN Community Support
Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.
Thursday, August 22, 2013 10:32 AM ✅Answered
Here I write an extension method to handle adding all names of checkboxes in GroupBox into Listbox.
public static void AddCheckBoxNamesToListBox(this GroupBox groupBox, ListBox listBox)
{
listBox.Items.AddRange( groupBox.Controls.OfType<CheckBox>().Select(s => s.Name));
}
Please let me know if any problem
Hope this will help you!!
Friday, August 23, 2013 4:33 AM ✅Answered
Loop through your Form.Controls collection and then through each GroupBox.Controls collection:
foreach (Control gb in this.Controls)
{
if (gb is GroupBox)
{
foreach (Control cb in gb.Controls)
{
if (cb is CheckBox)
listBox1.Items.Add(cb.Name);
}
}
}
~~Bonnie Berent DeWitt [C# MVP]