如何获取windows窗体页上的所有控件

本文关键字:控件 窗体 windows 何获取 获取 | 更新日期: 2023-09-27 18:12:33

我有一个windows窗体;并且有几个控件。
我想让它们在foreach循环中调用每个控件的Clear((方法,使其清晰并重新初始化项。

我该怎么做?**

当我在Vs 2008的调试模式下查看表单页面时,我看到了"这个",因此我可以看到里面的所有内容。

.net版本:2.0

如何获取windows窗体页上的所有控件

您可能在控件上有控件。因此,将Dmitry Erokhin的代码放入递归函数中可能是个好主意:

private void ClearNumberEntries(ControlCollection controls)
{
    foreach (Control ctrl in controls)
    {
        if (ctrl is NumberEntry)
        {
            ((NumberEntry)ctrl).Clear();
        }
        //if you are sure a NumberEntry can never have child controls that could also be of type NumberEntry you can put this in an else in stead
        ClearNumberEntries(ctrl.Controls);
    }
}

您可以通过以下控件进行迭代:

foreach (Control ctrl in this.Controls)
{
    if (ctrl is NumberEntry)
    {
        ((NumberEntry)ctrl).Clear();
    }
}

要再次初始化控件,无需清除每个控件,只需清除表单中的控件并调用InitializeComponent((

 private void InitializeControls()
        {
            this.Controls.Clear();
            InitializeComponent();
        }