Buttoned technology exchange group: 460 189 483
C # traversing all the controls form or type all controls
-
// traverse the form all the controls,
-
foreach (Control control in this.Controls)
-
{
-
// traverse operation after ...
-
control.Enabled = false;
-
}
-
Through all the controls in a panel
-
-
foreach (Control control in this.panel4.Controls)
-
{
-
control.Enabled = false;
-
}
-
Through all the TextBox controls or all types DateTimePicker control
-
-
Copy the code
-
foreach (Control control in this.Controls)
-
{
-
// loop through all TextBox ...
-
if (control is TextBox)
-
{
-
TextBox t = (TextBox)control;
-
t.Enabled = false;
-
}
-
// loop through all DateTimePicker ...
-
if (control is DateTimePicker)
-
{
-
DateTimePicker d = (DateTimePicker)control;
-
d.Enabled = false;
-
}
-
}
Bowen mainly controls the following figures to compare the way these two methods to obtain control:
1. The easiest way:
-
private void GetControls1(Control fatherControl)
-
{
-
Control.ControlCollection sonControls = fatherControl.Controls;
-
// loop through all the controls
-
foreach (Control control in sonControls)
-
{
-
listBox1.Items.Add(control.Name);
-
}
-
}
result:
The results are shown in ListBox acquired the right, you can be found not acquired child control Panel, GroupBox, TabControl like control.
2. Increase in the original recursive way:
-
private void GetControls1(Control fatherControl)
-
{
-
Control.ControlCollection sonControls = fatherControl.Controls;
-
// loop through all the controls
-
foreach (Control control in sonControls)
-
{
-
listBox1.Items.Add(control.Name);
-
if (control.Controls != null)
-
{
-
GetControls1(control);
-
}
-
}
-
}
result:
The vast majority of controls are to be acquired, but there are still two controls Timer, ContextMenuStrip not get to.
3. Use reflection (the Reflection)
-
private void GetControls2(Control fatherControl)
-
{
-
//reflection
-
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);
-
}
-
}
结果:
结果显示所有控件都被获取到了。