遍历window窗体中控件的方法.

来源:互联网 发布:无锡黑盒软件测试招聘 编辑:程序博客网 时间:2024/06/05 02:32

  在做项目中,想控制窗体中的某一类控件,并且可能窗体包含有容器,比如想让窗体上所有的

button不可见。

解决方案一:只能解决简单问题,便历不能子控件。

      foreach (object obj in this.Controls)
            {
                if (obj.GetType() == typeof(Button))
                {
                    ((Button)obj).Visible = false;
                }
            }

解决方案二:

通用的函数(2个):

函数很简单,

//Control ctl_Obj具体对像string str_Type要控制的类型名称)

(1)         public void Set_Controls(Control ctl_Obj, string str_Type )    

   {
            //当控件没有子控件时  
            if (!ctl_Obj.HasChildren)
            {
                if (ctl_Obj.GetType().ToString() == str_Type)
                {
                    ctl_Obj.Enabled = false;
                }
            }
            else   //当控件有子控件时  
            {
                int int_Number = 0;
                while (int_Number < ctl_Obj.Controls.Count)
                {
                    Set_Controls(ctl_Obj.Controls[int_Number], str_Type);
                    int_Number++;
                }
            }
        }

(2)        public void Set_Controls(Control ctl_Obj)
        {
            //当控件没有子控件时  
            if (!ctl_Obj.HasChildren)
            {
                switch (ctl_Obj.GetType().ToString())
                {
                    case "System.Windows.Forms.Label":
                        break;
                    case "System.Windows.Forms.Button":
                        ctl_Obj.Enabled = false;
                        break;
                    case "System.Windows.Forms.TextBox":
                        break;
                    case "System.Windows.Forms.ListView":
                        break;
                    case "System.Windows.Forms.GroupBox":
                        break;
                    case "System.Windows.Forms.ComboBox":
                        break;
                    case "System.Windows.Forms.ImageList":
                        break;
                    case "System.Windows.Forms.DataGrid":
                        break;
                    case "System.Windows.Forms.MainMenu":
                        break;
                    case "System.Windows.Forms.TreeView":
                        break;
                }
            }
            else   //当控件有子控件时  
            {
                int int_Number = 0;
                while (int_Number < ctl_Obj.Controls.Count)
                {
                    Set_Controls(ctl_Obj.Controls[int_Number]);
                    int_Number++;
                }
            }
        }

 调用:
            Form2 obj1 = new Form2();
            Set_Controls(obj1,"System.Windows.Forms.Button");
            obj1.ShowDialog();

以上代码在VS2005中通过验证

 

原创粉丝点击