用C#如何遍历一个窗体中的某一种控件

来源:互联网 发布:拼团软件排行 编辑:程序博客网 时间:2024/05/16 04:24

      如果我要遍历所有的Label控件.我们知道一个窗体中的所有控件都是Form.Controls中的成员,想要得到窗体中的所以成员,可以用foreach来遍历Controls属性中的对象。注意,Controls属性中包含的对象都是以Control基类形式存在的,这就是说我们只能用foreach(Control temp in this.Controls)来遍历。对于任何一个由Control派生来的类,或者说是所以控件,可以用其 GetType()函数来得到控件的类型。如果要判判断具体类型需要将类型转为字符串:tempControl.GetType().ToString()    它得到的是一个控件的完整名字,如:System.Windows.Forms.Label

     举例一:针对在控件中,有一些控件有子控件如 Panel ,GroupBox,而这些控件中又可能包含其它的Panel,GroupBox,所以我们必须判断出这些“母控件”,并用递归方法对其中的控件遍历!

           代码如下,在窗体中至少有一个LISTBOX和 一个按钮,注意每个函数接受的参数类型。


private void GetLabeinP(Panel temp)     //对panel进行遍历的函数
  {
   foreach(Control tempcon in temp.Controls)
   {
    switch(tempcon.GetType().ToString())
    {
     case "System.Windows.Forms.Label":
      this.listBox1.Items.Add(tempcon.Name);
      break;
     case "System.Windows.Forms.Panel":
      this.GetLabeinP((Panel)tempcon);
      break;
     case "System.Windows.Forms.GroupBox":
      this.GetLabeinG((GroupBox)tempcon);
      break;

    }
     
   }
  }
  private void GetLabeinG(GroupBox temp)   //对GroupBox遍历
  {
   foreach(Control tempcon in temp.Controls)
   {
    switch(tempcon.GetType().ToString())
    {
     case "System.Windows.Forms.Label":
      this.listBox1.Items.Add(tempcon.Name);
      break;
     case "System.Windows.Forms.Panel":
      this.GetLabeinP((Panel)tempcon);
      break;
     case "System.Windows.Forms.GroupBox":
      this.GetLabeinG((GroupBox)tempcon);
      break;

    }
     
   }
  }

  private void button1_Click_1(object sender, System.EventArgs e)  //按钮的代码
  {
   this.listBox1.Items.Clear();
   foreach(Control tempcon in this.Controls)
   {
    switch(tempcon.GetType().ToString())
    {
     case "System.Windows.Forms.Label":
      this.listBox1.Items.Add(tempcon.Name);
      break;
     case "System.Windows.Forms.Panel":
      this.GetLabeinP((Panel)tempcon);
      break;
     case "System.Windows.Forms.GroupBox":
      this.GetLabeinG((GroupBox)tempcon);
      break;

    }
     
   }  

  
  }

举例二:针对遍历控件中的Button控件

  foreach (Control ctl in this.Controls)
{
if (ctl is Button)
{
Button btn = ctl as Button;
btn.Enabled = false;
}
   作用就是遍历所有控件,判断出类型是Button按钮的。取得它的实例,对它进行操作





原创粉丝点击