简体   繁体   English

查找多种类型的所有控件?

[英]Finding all controls of multiple types?

I am trying to find all controls in a C# program that are radio buttons or checkboxes. 我试图在C#程序中找到所有单选按钮或复选框的控件。 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. 我只让它仅与单选按钮一起使用-如果我用Checkboxes重复IEnumerable行,它告诉我在此作用域中已经定义了一个名为button的局部变量。 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 : 您可以通过使用通用基类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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM