• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

获取组框的控件名称//获取控件名称和关联的组框

用户头像
it1352
帮助3

问题说明

大家好,



首先这是我的代码。



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

正确答案

#1
这是因为容器(如组框或面板)中的控件属于容器的控件集合,而不是表单控件的集合。如果你想要全部获取它们,你需要通过容器的集合进行递归

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
系列文章
更多 icon
同类精品
更多 icon
继续加载