【问题标题】:How Can I Get The Button Controls in Windows Form - Panel如何获取 Windows 窗体中的按钮控件 - 面板
【发布时间】:2011-09-19 06:16:37
【问题描述】:

获取表单中的所有按钮,包括 相同形式的面板中的按钮..

【问题讨论】:

标签: c# winforms


【解决方案1】:

这是我所做的, 我写了一个简单的函数,当我单击一个按钮时,我只选择面板控件并将其传递给一个函数,以便进一步循环该面板上的控件。

private void cmdfind_Click(object sender, EventArgs e)
    {
        try
        {
            foreach (Control control in this.Controls)
            {
                if (control.GetType() == typeof(Panel))
                    //AddToList((Panel)control); //this function pass the panel object so further processing can be done 
            }                         
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

【讨论】:

    【解决方案2】:
     List<Control> list = new List<Control>();
    
                GetAllControl(this, list);
    
                foreach (Control control in list)
                {
                    if (control.GetType() == typeof(Button))
                    {
                        //all btn
                    }
                }
    
            private void GetAllControl(Control c , List<Control> list)
            {
                foreach (Control control in c.Controls)
                {
                    list.Add(control);
    
                    if (control.GetType() == typeof(Panel))
                        GetAllControl(control , list);
                }
            }
    

    【讨论】:

      【解决方案3】:

      试试这个

      foreach (var control in this.Controls)
      {
         if (control.GetType()== typeof(Button))
         {
      
             //do stuff with control in form
         }
      
         else if (control.GetType() == typeof(Panel))
         {
             var panel = control as Panel;
             foreach (var pan in panel.Controls)
             {
                 if (pan.GetType() == typeof(Button))
                 {
      
                      //do stuff with control in panel
                 }
              }
          }              
      
      } 
      

      【讨论】:

      • 如果 Panel 包含另一个带有按钮的面板,则可以使用递归。
      猜你喜欢
      • 2015-05-02
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多