Winform遍歷視窗的所有控制元件(幾種方式實現)
阿新 • • 發佈:2018-12-22
//遍歷窗體所有控制元件,
foreach (Control control in this.Controls)
{
//遍歷後的操作...
control.Enabled = false;
}
遍歷某個panel的所有控制元件
foreach (Control control in this.panel4.Controls)
{
control.Enabled = false;
}
遍歷所有TextBox型別控制元件或者所有DateTimePicker控制元件 複製程式碼 foreach (Control control in this.Controls) { //遍歷所有TextBox... if (control is TextBox) { TextBox t = (TextBox)control; t.Enabled = false; } //遍歷所有DateTimePicker... if (control is DateTimePicker) { DateTimePicker d = (DateTimePicker)control; d.Enabled = false; } }
博文主要以下圖中的控制元件來比較這兩種方式獲取控制元件的方式:
1. 最簡單的方式:
private void GetControls1(Control fatherControl)
{
Control.ControlCollection sonControls = fatherControl.Controls;
//遍歷所有控制元件
foreach (Control control in sonControls)
{
listBox1.Items.Add(control.Name);
}
}
結果:
獲取的結果顯示在右側的ListBox中,可以發現沒有獲取到Panel、GroupBox、TabControl等控制元件中的子控制元件。
2. 在原有方式上增加遞迴:
private void GetControls1(Control fatherControl) { Control.ControlCollection sonControls = fatherControl.Controls; //遍歷所有控制元件 foreach (Control control in sonControls) { listBox1.Items.Add(control.Name); if (control.Controls != null) { GetControls1(control); } } }
結果:
絕大多數控制元件都被獲取到了,但是仍然有兩個控制元件Timer、ContextMenuStrip沒有被獲取到。
3. 使用反射(Reflection)
private void GetControls2(Control fatherControl)
{
//反射
System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
for (int i = 0; i < fieldInfo.Length; i++)
{
listBox1.Items.Add(fieldInfo[i].Name);
}
}
結果:
結果顯示所有控制元件都被獲取到了。