How to get all children of a parent control?

前端 未结 4 1077
长发绾君心
长发绾君心 2020-12-03 15:03

I\'m looking for an code example how to get all children of parent control.

I have no idea how do it.

foreach (Control control in Controls)
{
  if (         


        
4条回答
  •  既然无缘
    2020-12-03 15:30

    Maybe it could be useful for someone:

    public void GetControlsCollection(Control root,ref List AllControls,  Func filter)
    {
        foreach (Control child in root.Controls)
        {
            var childFiltered = filter(child);
            if (childFiltered != null) AllControls.Add(child);
            if (child.HasControls()) GetControlsCollection(child, ref AllControls, filter);
        }
    }
    

    This is recursive function to get the collection of controls with the possibility of appling filter (for expample by type). And the example:

     List resultControlList = new List();
     GetControlsCollection(rootControl, ref resultControlList, new Func(ctr => (ctr is DropDownList)? ctr:null ));
    

    It will return all DropDownLists in rootControl and his all children

提交回复
热议问题