获取组框的控件名称//获取控件名称和关联的组框
问题说明
大家好,
首先这是我的代码。
Hi all,
First here is my Code.
private void Form1_Load(object sender, EventArgs e)
{
foreach (var button in Controls.OfType<System.Windows.Forms.Control>())
{
button.Click = button_Click;
}
}
private void button_Click(object sender , EventArgs e)
{
Console.WriteLine("the Control with the name " this.Controls[((System.Windows.Forms.Control)(sender)).Name].Name "was clicked");
}
如果控制类中的每个控件都打印出其名称它被点击了。
这样可行但是当一个控件例如一个按钮或pictureBox在GroupBox中,如果我点击它就不再给我这个名字了。当我点击Groupbox本身时,它会给我GroupBox的名称。似乎我再也无法访问Controls名称了。
实际上我的问题是如何获得点击的控件的名称和相关的GroupBox如果控件位于GroupBox中。无论如何我想提一下这个问题。
我需要的方式和上面的代码一样。我不想为每个Control实现一个单独的方法。
如果有人能给我一个建议我会非常感激。
谢谢。
我尝试过:
谷歌,MSDN,关注常见问题在CodeProject.com
Every Control in the Control Class print its name if it was clicked.
This works fine but when a Control e.g. a button or pictureBox is in a GroupBox it doesnt give me the name anymore if i click on it. When i click on the Groupbox itself, it gives me the name of the GroupBox. It seems that i have no access to the Controls names anymore.
Actually my question is about how can i get the name of the clicked Control and the associated GroupBox if the Controls are in a GroupBox. I wanted to mention that problem anyway.
I need it in the same way like the code above. I dont want to implement for every Control a seperate Method.
I would highly appreciate it if somebody can give me a suggestion.
Thank you.
What I have tried:
Google, MSDN, looking about common issues at CodeProject.com
正确答案
这是因为容器(如组框或面板)中的控件属于容器的控件集合,而不是表单控件的集合。如果你想要全部获取它们,你需要通过容器的集合进行递归
This is because the controls in a container such as a groupbox or panel belong to the container's controls collection, not the form's control's collection. You need to recurse through the container's collections if you want to get them all
private void SetClickHandler(Control.ControlCollection controls) {
foreach (var button in controls.OfType<Control>()) {
button.Click = button_Click;
if (button.Controls.Count > 0)
SetClickHandler(button.Controls);
}
}
private void Form1_Load(object sender, EventArgs e) {
SetClickHandler(Controls);
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhbfgbgh
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
希伯来语的空格句子标记化错误
it1352 06-22