将表单中的所有按钮添加到列表中

时间:2015-05-21 11:17:20

标签: c# winforms list button add

我的窗体中有86个按钮。我在代码中列出了一个按钮列表。现在我想将所有按钮添加到列表中。有没有办法一次性将按钮添加到列表中,还是需要按钮添加所有按钮?

这是我的清单:List<Button> lColors = new List<Button>();

2 个答案:

答案 0 :(得分:2)

如果所有按钮都在表单上(例如,不在Panel中)

List<Button> lColors = this.Controls.OfType<Button>().ToList();

如果某些按钮位于表单上,而某些按钮位于面板中

List<Button> lColors = this.Controls.OfType<Button>()
               .Concat(this.panel1.Controls.OfType<Button>())
               .ToList();

答案 1 :(得分:0)

您可以使用以下递归方法获取指定控件的指定类型的所有子控件:

private static IEnumerable<T> GetAllControls<T>(Control control)
{
    var controls = control.Controls.OfType<T>();
    return control.Controls.Cast<Control>()
        .Aggregate(controls, (current, c) => current.Concat(GetAllControls<T>(c)));
}

用法:

var buttons = GetAllControls<Button>(this);