你单步调试了吗?return 就是直接返回了。

解决方案 »

  1.   

    如果你递归调用 findControls(myctr, DGVName) ,你总要判断一下返回值吧。
      

  2.   

    我也觉得很奇怪~应该要在if (((DataGridView)myctr).Name.Equals(DGVName)==True)
    这里 return 才对,但是我单步调试的结果并不会在这里离开,程序依旧继续foreach 真奇怪??
      

  3.   

    就像@sp1234说的,你递归调用findControls的时候,返回值被忽略了,所以递归中找到的结果就被抛弃了。
    而且ControlCollection上也提供了Find方法,ctr.Controls.Find(DGVName, true).FirstOrDefault() 应该就是要找的DataGridView
      

  4.   

    你return之后,会走到
    findControls(myctr, DGVName);
    这里
    话说,你真的是单步F10调试,而不是F5直接跑到断点吗,应该很明显才对
      

  5.   

    感谢大家的帮忙,我将程式改为这样以可以达到我想要得结果了,谢谢协助~        public DataTable findControls(Control ctr,  string DGVName)
            {
                DataTable tmp_dt = new DataTable();
                if (ctr.Controls.Find(DGVName , true).Length > 0)
                {
                    tmp_dt = (DataTable)((DataGridView)ctr.Controls.Find(DGVName , true)[0]).DataSource;
                    return tmp_dt;
                }            
                return tmp_dt;
            }
      

  6.   

        代码颠倒下位置
      //寻找动态产生的控件        
            public DataTable findControls(Control ctr,  string DGVName )
            {
                DataTable tmp_dt = new DataTable();
                foreach (Control myctr in ctr.Controls)
                {
                    if (myctr is DataGridView)
                    {
                        if (((DataGridView)myctr).Name.Equals(DGVName))
                        {
                            tmp_dt = (DataTable)((DataGridView)myctr).DataSource;
                            return tmp_dt;                        
                        }               
                    }
                    //如果传进来的控件有子控件的话
                    if (myctr.HasChildren == true)
                    {
                        //就递归调用自己
                        findControls(myctr, DGVName);                   
                    }
                }
                return tmp_dt;
            }
      

  7.   

    别忘记 
     //就递归调用自己
             return      findControls(myctr, DGVName);                  
      

  8.   

    to : china_ggd 兄
    谢谢你~但我试过F11逐步调试一样不行喔,我快放弃这样的写法了,我的容器结构是
        Form >splitContainer1.Panel2 > tabControl1 >  > tabPage >DataGridView
    我是觉得github_22161131 #4楼提的简洁有力~