扣扣技術交流群:460189483
-
//遍歷窗體所有控件,
-
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);
-
}
-
}
結果:
結果顯示所有控件都被獲取到了。