尝试在窗体上循环遍历Button控件时出现“无法转换类型的对象”错误 [英] Getting 'Unable to cast object of type' error when trying to loop through Button controls on Form

查看:82
本文介绍了尝试在窗体上循环遍历Button控件时出现“无法转换类型的对象”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

表单中,我添加了 TableLayoutPanel ,并在其中添加了5个按钮。

In a Form, I added a TableLayoutPanel, and within that I add 5 buttons.

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

At runtime, I add 10 buttons to Form1 in a loop. Then I use foreach to do something with those 10 buttons.

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

程序,出现错误:


无法将类型为 System.Windows.Forms.TableLayoutPanel的对象转换为类型为 System.Windows。 Forms.Button'

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

我认为发生此错误是因为 TableLayoutPanel 包含5

I think this error happens because the TableLayoutPanel contains 5 buttons in it.

是的,我可以删除此 TableLayoutPanel 并在 Form ,但是 TableLayoutPanel 对我的代码有很大帮助。

Yeah I can delete this TableLayoutPanel and add 5 buttons directly in the Form, but the TableLayoutPanel helps a lot in my code.

有没有解决方案可以遍历这10个按钮,并且仍然保留 TableLayoutPanel

So is there any solution to traverse those 10 buttons and still keep the TableLayoutPanel?

此外,我可以遍历表单和 TableLayoutPanel中的按钮分别?

Furthermore, can I traverse "buttons in Form" and "buttons in TableLayoutPanel" separately ?

推荐答案

您当前的代码是将尝试遍历Form 上的所有控件(嗯,无论如何,所有顶级控件..您都需要使用递归来遍历嵌套在其他控件内的所有控件),然后将每个到 Button ,因此会出现异常。

Your current code is going to try to iterate over ALL controls on the Form (well, all top-level controls anyway.. you'd need to use recursion to iterate through all controls nested within other controls), then cast each to a Button, hence the exception you're getting.

只需指定要迭代的控件:

Just specify which controls you want to iterate over:

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

遍历 TableLayoutPanel 中的控件(我不认为是这种情况;我认为您直接在Forms上有Buttons,而在TableLayoutPanel中有更多Buttons,并且您想在Forms本身上遍历Buttons),然后引用该子控件:

If you want to just iterate over the controls in the TableLayoutPanel (I don't think that's the case; I think you've got Buttons directly on the Form and more Buttons in the TableLayoutPanel, and you want to loop over the Buttons on the Form itself), then reference that child control instead:

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

这篇关于尝试在窗体上循环遍历Button控件时出现“无法转换类型的对象”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆