-->

获得“无法投类型的对象试图循环时,通过按钮控件上的格式错误(Getting 'Unable

2019-10-21 21:02发布

在一个Form ,我添加一个TableLayoutPanel ,并在该予添加5个按钮。

在运行时,我加10个按钮添加到Form1中循环。 然后,我用foreach做的10个按钮的东西。

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

当我运行该程序,就会出现错误:

无法转换类型“System.Windows.Forms.TableLayoutPanel”的对象键入“System.Windows.Forms.Button”

我认为这会发生错误,因为TableLayoutPanel包含这5个按钮。

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

那么,有没有解决那些穿越10个按钮,并且仍然保持TableLayoutPanel

此外,我可以遍历“按钮表”和“TableLayoutPanel中的按钮”分开?

Answer 1:

您当前的代码将尝试遍历所有窗体上控件(当然,所有顶层控制反正..你需要使用递归通过嵌套其他控件中的所有控件迭代),那么每个转换为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
}


Answer 2:

System.Windows.Forms.TableLayoutPanel为键入” System.Windows.Forms.Button“

由于错误解释您尝试种姓的类型,它不能是种姓元素。

原因:foreach循环

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

this.Controls将在当前的形式返回每个控制,这包括其他形式的元素,如TableLayoutPanel不能转换为一个button 。 所以它们进行过滤如下。

答:

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

注意:如果按钮位于另一个控制器内部这种做法不会为他们提供。 相反,你需要访问它的具体的控制和循环。



Answer 3:

Form.Controls是类型的ControlCollection ,因此您的代码可能无法运行! 使用下面的代码来代替:

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

要么

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


文章来源: Getting 'Unable to cast object of type' error when trying to loop through Button controls on Form