遍历GroupBox上的所有的textbox

遍历GroupBox上的所有的textbox

复制代码
 foreach (Control c in groupBox1.Controls)
{
                if (c is TextBox)
                {
                        //这里写代码逻辑
                }
}
复制代码

遍历的时候,需要用Control遍历;

如果直接使用foreach(TextBox t in groupBox1.Controls)

并且groupbox上有Lable或其他非textbox控件的时候,会提示不能强制转换为textbox

所以,需要使用 is来判断,获取的控件是否为textbox



foreach  (Control ctl  in  this .Controls)
{
    if  ((ctl  as  GroupBox) !=  null )
    {
        foreach  (Control c  in  ctl.Controls)
        {
            ComboBox cbb = c  as  ComboBox;
            if  (cbb !=  null )
            {
               //
            }
        }
    }
}



大致思路:
public List<Control> FindControls()
{
    List<Control> result = new List<Control>();
    foreach (Control c in Controls) 
    {
        foreach (Control item in FindInSubControl(c)) result.Add(item);
    }
    return result;
}

private List<Control> FindInSubControl(Control parent)
{
    List<Control> result = new List<Control>();
    foreach (Control c in parent.Controls) 
    {
        foreach (Control item in FindInSubControl(c)) result.Add(item);
        result.Add(parent);
    }
    return result;
}




猜你喜欢

转载自blog.csdn.net/e_wsq/article/details/80313558
今日推荐