【问题标题】:Finding all controls of multiple types?查找多种类型的所有控件?
【发布时间】:2014-05-04 21:28:19
【问题描述】:

我正在尝试在 C# 程序中查找所有作为单选按钮或复选框的控件。另外,我还想找到某个文本框。我只让它与单选按钮一起工作 - 如果我用 Checkboxes 重复 IEnumerable 行,它告诉我已经在这个范围内定义了一个名为按钮的局部变量。感谢您的帮助。

IEnumerable<RadioButton> buttons = this.Controls.OfType<RadioButton>();

foreach (var Button in buttons)
{
    //Do something
}

【问题讨论】:

  • 您不能对 Checkboxes 和 RadioButtons 使用相同的变量。
  • 有没有办法在 if/else 语句中使用 IEnumerable?如: if (questiontype == "MCQ"){ //单选按钮的IEnumerable } else if (questiontype == "Multiple select"){ //复选框的IEnumerable }

标签: c# winforms ienumerable


【解决方案1】:

您可以通过使用公共基类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
}

【讨论】:

  • 谢谢,太好了。 if/else 循环中是否有任何方法可以识别例如单选按钮是否被选中?或者如果文本框有用户输入?
【解决方案2】:

您需要为复选框使用不同的变量名称。

IEnumerable<RadioButton> buttons = this.Controls.OfType<RadioButton>();
IEnumerable<CheckBox> checkboxes = this.Controls.OfType<CheckBox>();

如果它是一个众所周知的名称,您还应该能够按名称抓取您的文本框。

【讨论】:

    猜你喜欢
    • 2020-02-20
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    相关资源
    最近更新 更多