比如我窗体上有两个文本框,还有一个PANEL,PANEL中有一个按钮,我现在遍历界面上所有的控件,如果不进入PANEL的话那就是两个文件框和一个PANEL,我现在想得到两个文本框,一个PANEL,一个按钮,难道必须进对PANEL进行遍历才可以?

解决方案 »

  1.   

    当然按钮是在Panel.Controls里。
      

  2.   

    乖乖的遍历所有的容器吧还有一种不推荐的方法(为了你一次遍历用,属于投机取巧),使用反射
    foreach(FieldInfo fi in typeof(Form1).GetFields(BindingFlags.Private | BindingFlags.Instance | BindingFlags.DeclaredOnly)
    {
    //判断fi的FieldType为控件类型
    }
      

  3.   

    应该可以直接从FORM上把所有控件取出来吧.
      

  4.   


                foreach (Control con in this.Controls)
                {
                    if (con is TextBox)
                    {
                        MessageBox.Show(con.Text);
                    }
                }
      

  5.   

    遍历控件当然是有层次的,只会遍历第一层容器,这样也比较合理。
    想全部遍历出来,只要递归一下就可以了。
    譬如:将得到的某个控件control.Controls.count判断,如果为0就添加,如果为1再继续遍历。
    不麻烦
      

  6.   


    foreach (Control con in this.Controls)
                {
                    if (con is Panel)
                    {
                        Panel panel = con as Panel;
                        foreach (Control cont in panel.Controls)
                        {
                            if (cont is TextBox)
                            {
                                MessageBox.Show(cont.Text);
                            }
                        }
                    }
                }
      

  7.   


                foreach (Control con in this.Controls)
                {
                    if (con is Panel)
                    {
                        Panel panel = con as Panel;
                        foreach (Control cont in panel.Controls)
                        {
                            if (cont is Button)
                            {
                                MessageBox.Show("按钮");
                            }
                        }
                    }
                    else if (con is TextBox)
                    {
                        MessageBox.Show("文本框");
                    }
                    
                }
      

  8.   


    foreach (System.Windows.Forms.Control contr in this.Controls)
    {
        string name = contr.Name;
        foreach (System.Windows.Forms.Control contr2 in contr.Controls)
        {
            string name2 = contr2.Name;
        }
    }
      

  9.   

    http://blog.csdn.net/dunao/archive/2010/10/19/5952723.aspx可以看一下这个,是采用遍历的方法来实现多语言的完整的源程序下载
    http://blog.csdn.net/dunao/archive/2010/10/28/5972927.aspx
      

  10.   

    在运行的时候没有一维的集合供你用, 就是能一下子拿到全部的不要不顾死活的上来就直接访问 Controls,
    先问问控件 HasChildren 之后再遍历.
     
      

  11.   

    递归实现吧,不知道你有多少个Panel,也不知道你Panel中有无panel
    if(ctl.Controls.Count>0)
       递归
    else
       return;
    挺容易实现的