Winform遍歷窗口的所有控件(幾種方式實現)


 

本文鏈接: https://blog.csdn.net/u014453443/article/details/85088733

扣扣技術交流群:460189483

C#遍歷窗體所有控件或某類型所有控件

  1.  
    //遍歷窗體所有控件,
  2.  
    foreach (Control control in this.Controls)
  3.  
    {
  4.  
    //遍歷后的操作...
  5.  
    control.Enabled = false;
  6.  
    }
  1.  
    遍歷某個panel的所有控件
  2.  
     
  3.  
    foreach (Control control in this.panel4.Controls)
  4.  
    {
  5.  
    control.Enabled = false;
  6.  
    }
  1.  
    遍歷所有TextBox類型控件或者所有DateTimePicker控件
  2.  
     
  3.  
    復制代碼
  4.  
    foreach (Control control in this.Controls)
  5.  
    {
  6.  
       //遍歷所有TextBox...
  7.  
    if (control is TextBox)
  8.  
    {
  9.  
    TextBox t = (TextBox)control;
  10.  
    t.Enabled = false;
  11.  
    }
  12.  
       //遍歷所有DateTimePicker...
  13.  
    if (control is DateTimePicker)
  14.  
    {
  15.  
    DateTimePicker d = (DateTimePicker)control;
  16.  
    d.Enabled = false;
  17.  
    }
  18.  
    }

博文主要以下圖中的控件來比較這兩種方式獲取控件的方式:

1. 最簡單的方式:

  1.  
    private void GetControls1(Control fatherControl)
  2.  
    {
  3.  
    Control.ControlCollection sonControls = fatherControl.Controls;
  4.  
    //遍歷所有控件
  5.  
    foreach (Control control in sonControls)
  6.  
    {
  7.  
    listBox1.Items.Add(control.Name);
  8.  
    }
  9.  
    }

 結果:

 

獲取的結果顯示在右側的ListBox中,可以發現沒有獲取到Panel、GroupBox、TabControl等控件中的子控件。

2. 在原有方式上增加遞歸:

  1.  
    private void GetControls1(Control fatherControl)
  2.  
    {
  3.  
    Control.ControlCollection sonControls = fatherControl.Controls;
  4.  
    //遍歷所有控件
  5.  
    foreach (Control control in sonControls)
  6.  
    {
  7.  
    listBox1.Items.Add(control.Name);
  8.  
    if (control.Controls != null)
  9.  
    {
  10.  
    GetControls1(control);
  11.  
    }
  12.  
    }
  13.  
    }

結果:

 

絕大多數控件都被獲取到了,但是仍然有兩個控件Timer、ContextMenuStrip沒有被獲取到。

3. 使用反射(Reflection)

  1.  
    private void GetControls2(Control fatherControl)
  2.  
    {
  3.  
    //反射
  4.  
    System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
  5.  
    for (int i = 0; i < fieldInfo.Length; i++)
  6.  
    {
  7.  
    listBox1.Items.Add(fieldInfo[i].Name);
  8.  
    }
  9.  
    }

結果:

 

結果顯示所有控件都被獲取到了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM