Reputation: 181
I am trying to find all controls in a C# program that are radio buttons or checkboxes. In addition, I want to also find a certain textbox. I've only gotten it to work with just radio buttons - if I repeat the IEnumerable line with Checkboxes instead, it tells me that a local variable named buttons is already defined in this scope. Thanks for the help.
IEnumerable<RadioButton> buttons = this.Controls.OfType<RadioButton>();
foreach (var Button in buttons)
{
//Do something
}
Upvotes: 2
Views: 502
Reputation: 19496
You can accomplish what you're trying to do by using the common base class Control
:
IEnumerable<Control> controls = this.Controls
.Cast<Control>()
.Where(c => c is RadioButton || c is CheckBox || (c is TextBox && c.Name == "txtFoo"));
foreach (Control control in controls)
{
if (control is CheckBox)
// Do checkbox stuff
else if (control is RadioButton)
// DO radiobutton stuff
else if (control is TextBox)
// Do textbox stuff
}
Upvotes: 7
Reputation: 1487
You will need to use a different variable name for your checkboxes.
IEnumerable<RadioButton> buttons = this.Controls.OfType<RadioButton>();
IEnumerable<CheckBox> checkboxes = this.Controls.OfType<CheckBox>();
You should also be able to just grab your textbox by name if it's a well known name.
Upvotes: 0