要求也能遍历到菜单中的各项和工具栏中的各个按钮。
在网上找了很多,多无法达到上面的要求。
谢谢各位了。

解决方案 »

  1.   

    foreach(control c in form1.controls)
    {
      if(c as menu) 
    {
    //遍历
    }
      //操作
    }
      

  2.   

    起码菜单就不是Control,而是直接从Component来的。在循环中不能按Control来循环,或者这个思路不合适或没有什么太大的意义。
      

  3.   

    form中有controls集合数组,完全可以循环取到每个控件。
      

  4.   

    ToolStrip和MenuStrip还有一些东西不属于Controls所覆盖的范围,你可以去看一下窗体的InitializeComponent,我个人觉得可能只能在这个函数中动手脚了,申明一个Component集合,然后自己分类型遍历
      

  5.   

    用反射FieldInfo[] myFieldInfo;
    Type myType = typeof(From1); //Form1 为你的窗口类
    myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance
    | BindingFlags.Public);
    StringBuilder str = new StringBuilder();
    Regex regex1 = new Regex(@"System\.Windows\.Forms");foreach (FieldInfo f in myFieldInfo)
    {
    if(regex1.IsMatch(f.FieldType.ToString()) == false)
    continue;
    str.Append(f.Name);
    str.Append('\t');
    str.Append(f.FieldType.ToString());
    str.Append("\r\n");
    }
    MessageBox.Show(str.ToString());注意要引用:
    using System.Text.RegularExpressions;
    using System.Reflection;
      

  6.   

    菜单和工具栏也不属于this.components.Component中,那些位于组件工具栏中的对象会被加在窗体的this.components.Component,例如ImageList
      

  7.   

    道歉,试了一下,使用foreach(control c in this.controls)应该可以访问到所有的控件,包括菜单,工具条,但是不能访问类似ImageList类的组件,这类组件需要使用
    foreach(component c in this.component.Components)才可以访问.
    if(c as menu) 应该改成if(c is MenuStrip)
      

  8.   

    控件用foreach(control c in this.controls)
    组件用foreach(Compoent c in this.compoent.components)
      

  9.   

    不行呀。
    不要说
    foreach(Compoent c in this.compoent.components)了
    就是
    for (int i = 0; i < this.components.Components.Count; i++ )
    也报错(this.components = null)。
      

  10.   

    无论使用this.components还是this.Controls都必须在窗体被Load之后使用,否则这两个对象都没有被初始化,在Form_Load事件中写就没有问题
      

  11.   

    控件用foreach(control c in this.controls)
    组件用foreach(Compoent c in this.compoent.components)
    无论使用this.components还是this.Controls都必须在窗体被Load之后使用,否则这两个对象都没有被初始化,在Form_Load事件中写就没有问题
      

  12.   

    递归就可以了,只是for就不能遍历到控件中的控件
      

  13.   

    为什么不使用redleaf1995(捡到一分钱给谁?)的方式?
    这样不需要递归(唯一不好的就是无法区分层次)
      

  14.   

    redleaf1995(捡到一分钱给谁?) 的方式不错,但是会有风险,不知道System.Windows.Form命名空间下有没有非控件非组件的类,如果有,就有可能出现错误.
      

  15.   

    还是递归好,至少什么都能得到——private void BindDBControls(DataRow dr, Control container)
    {
    string feeurl = "test.aspx";
    foreach(Control ctrl in container.Controls)
    {
    if(ctrl.HasChildren==true)//如果有子控件
    {
    BindDBControls(dr, ctrl);
    }
    else
    {
    if(!ctrl.Name.StartsWith("FK_"))
    continue;
    ctrl.Text = dr[ctrl.Name.Substring(ctrl.Name.IndexOf("_")+1, ctrl.Name.Length-ctrl.Name.IndexOf("_")-1)].ToString();
    }
    }//end of 1st foreach
    }