百度了很多方法都无法正确解析出多层嵌套的控件,网上很多方法都仅适用于单层解析。于是参考了网上的方法并进行改进,具体方法如下:
Control类型可以遍历窗体中的所有控件,但是如果在控件中再加入控件时(我称之为父控件中加入子控件),遍历窗体控件时只会遍历父控件,而不会遍历子控件。要想遍历子控件,可以在遍历窗体控件时,再加一层遍历,三层及以上嵌套,以此类推!这样当遍历到父控件时,嵌套会自动进入子控件并遍历,而其他没有子控件的控件则会自动跳出!
例中需要将一些字符串填入子控件Label中,同时修改子控件button的content(即Text),于是遍历整个页面所有的控件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private string[] ServeNameStrArr;
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
ServeNameStrArr = new string[]{ "Simpole-AMESimDependence",
"Simpole-HiPack","Simpole-CTool","Simpole-DBSever",
"Simpole-Dependence","Simpole-Dependence",
"Simpole-HiSimulator","Simpole-monitorpaneldb","Simpole-SimSever",
"Simpole-SimulinkDependence","Simpole-SimulinkTool","Simpole-VariableBinding",
"Simpole-View"};
int i = 0;
foreach (Control parent in this.Controls)
{
//找到父类控件
foreach (Control c in parent.Controls)
{
//找到想要的子类控件Label!
if (c.GetType().ToString().Contains( "Forms.Label")&i<ServeNameStrArr.Length)
{
c.Text = ServeNameStrArr[i];
i++;
}
else if (c.GetType().ToString().Contains("Forms.Button"))
{
button3.Text = "success";
button3.Enabled = false;
}
}
}
}
}
}
点击button2前
点击button2后