尝试循环访问 Form 上的 Button 控件时出现 'Unable to cast object of type' 错误

Getting 'Unable to cast object of type' error when trying to loop through Button controls on Form

Form 中,我添加了一个 TableLayoutPanel,并在其中添加了 5 个按钮。

在运行的时候,我循环添加了10个按钮到Form1。然后我使用 foreach 来处理这 10 个按钮。

foreach (Button C in this.Controls)
    // do something

当我运行运行程序时,出现错误:

Unable to cast object of type 'System.Windows.Forms.TableLayoutPanel' to type 'System.Windows.Forms.Button'

我认为发生此错误是因为 TableLayoutPanel 包含 5 个按钮。

是的,我可以删除这个 TableLayoutPanel 并直接在 Form 中添加 5 个按钮,但是 TableLayoutPanel 对我的代码有很大帮助。

那么有什么解决方案可以遍历这 10 个按钮并仍然保留 TableLayoutPanel

另外,我可以分别遍历"buttons in Form"和"buttons in TableLayoutPanel"吗?

Form.Controls 是 ControlCollection 类型,所以您的代码可能不是 运行! 请改用以下代码:

foreach (Control C in this.Controls)
{
    // do something
}

foreach(Button b in this.Controls.OfType<Button>())
{
   //do something
}

您当前的代码将尝试遍历表单上的所有控件 (好吧,无论如何,所有顶级控件..您需要使用递归来遍历嵌套在其中的所有控件其他控件), 然后将每个控件都转换为 Button,因此您会遇到异常。

只需指定要迭代的控件:

foreach (var button in this.Controls.OfType<Button>())
{
    // now you'll iterate over just the Button controls
}

如果您只想遍历 TableLayoutPanel 中的控件(我不认为是这种情况;我认为您直接在表单上获得了按钮和更多按钮在 TableLayoutPanel 中,并且您想遍历表单本身的按钮), 然后引用该子控件:

foreach (var button in tableLayoutPanel1.Controls.OfType<Button>())
{
    // iterate over the Button controls inside the TableLayoutPanel
}

System.Windows.Forms.TableLayoutPanel' to type 'System.Windows.Forms.Button'

正如错误所解释的那样,您尝试对元素进行种姓化,使其无法被种姓化。

原因:foreach 循环

foreach (Button C in this.Controls) // Button is the wrong type caste

this.Controls 将 return 当前表单中的每个控件,这包括无法转换为 button 的其他表单元素,例如 TableLayoutPanel。所以按如下方式过滤它们。

答案:

foreach (var C in this.Controls){
     if(c.GetType()== typeof(Button)){
          Button btn = (Button)item; //do work using this
      } 
}

注意:如果按钮位于另一个控制器内,则此方法将不会提供它们。相反,您需要访问特定的控件并在其中循环。