获取组框中的控件名称//获取控件名称和关联的组框 [英] Get name of control in groupbox//get name of control and associated groupbox

查看:73
本文介绍了获取组框中的控件名称//获取控件名称和关联的组框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



首先这是我的代码。



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);
}


这篇关于获取组框中的控件名称//获取控件名称和关联的组框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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