質問

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
}
役に立ちましたか?

解決

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
}

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top