C#列出项目中所有创建的窗体和按钮名称 [英] C# listing all created windows forms and buttons name in a project

查看:109
本文介绍了C#列出项目中所有创建的窗体和按钮名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将项目中所有已创建的窗体和按钮名称列入listbox1。我该怎么办请帮助我



我尝试过的事情:



I want to list all of the created windows forms and buttons name in a project into listbox1. How can I do please help me

What I have tried:

private void tumekranlar_Load(object sender, EventArgs e)
{
   var c = GetAll(this, typeof(Button));

   listBox1.Items.Add(c.Count().ToString());
}

public IEnumerable<control> GetAll(Control control, Type type)
{
   var controls = control.Controls.Cast<control>();

   return controls.SelectMany(ctrl => GetAll(ctrl, type))
                                      .Concat(controls)
                                      .Where(c => c.GetType() == type);
}

推荐答案

如果你想得到某种类型的所有控件,你可以用以下方式使用泛型:

if you wants to get all controls of a certain type you could use generics in the following way:
public List<T> FindControls<T>(Control control) where T : Control
{    
     var controls = control.Controls.Cast<Control>();
     return controls.SelectMany(ctrl => FindControls<T>(ctrl))
                    .Concat(controls)
                    .Where(c => c.GetType() == typeof(T))
                    .Cast<T>()
                    .ToList();
}



通过这种方式调用函数:


this way you call the function:

List<Button> list = FindControls<Button>(this);
MessageBox.Show("Total Buttons: " + list.Count);





你添加到listBox只有项目one - 计数值。

因此,您需要添加一个Button名称列表作为List< string>喜欢:





you did add to listBox Items only the one - the count value .
So, you need add a list of Button names as List<string> like:

listBox1.Items.AddRange(list.Select(s => s.Name).ToList());


这篇关于C#列出项目中所有创建的窗体和按钮名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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