HotDog's Blog

Hotdog (Robert Verpalen) about C# and vb.net

vbCity Blogs moved to:
http://cs.vbcity.com/blogs
  Home :: Syndication  :: Login

OctNovember 2009Dec
SMTWTFS
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

Articles

Archives

Topics

CONTACT

Fun but useful linkies

General

VS 2005

Wolfenstein ET

In .net each ControlContainer can have its own controlcollection. That means if you are using controlcontainers such as panels on a form, you will need to loop through all containers.

Below is the code I generally use for that task, with as small extra addition that you can specify which type of control you want to get back

added 1-6-5: VS2005 (whidbey) code

Code> (doubleclick to copy)
#region FormControls
public
static ArrayList GetControls(ContainerControl cc, Type ctype)
{
ArrayList al = new ArrayList();
AddControls(
ref al,cc.Controls,ctype);
return
al;
}
private
static void AddControls(ref ArrayList al,Control.ControlCollection cc,Type ctype)
{
foreach(Control c in cc)
{
if(ctype==null // ctype.IsAssignableFrom(c.GetType()))
al.Add(c);
if(c.HasChildren)
AddControls(ref al,c.Controls,ctype);
}
}
public
static ArrayList GetControls(ContainerControl cc)
{
return GetControls(cc,null);
}
#endregion

Since you can loop through an arraylist strongly typed, you can loop through the result with just the type you want.For example, to clear all textboxes:

Code> (doubleclick to copy)
foreach(TextBox tb in GetControls(this,typeof(TextBox)))
tb.Clear();

or in vb.net

Code> (doubleclick to copy)
        For Each tb As TextBox In GetControls(Me, GetType(TextBox))
            tb.Clear()
        Next
 
 
 

For those of you lucky enough to have vs2005:
Code Copy HideScrollFull
        public static Collection<ControlType> GetControls<ControlType>(ContainerControl Parent)
            where ControlType:Control
        {

            Collection<ControlType> coll = new Collection<ControlType>();
            findControls<ControlType>(coll, Parent);
            return coll;
        }
        public static void findControls<ControlType>(Collection<ControlType> coll, Control Parent)
            where ControlType : Control
        {
            foreach (Control c in Parent.Controls)
            {
                if (c is ControlType)
                    coll.Add(c as ControlType);
                if (c.HasChildren)
                    findControls(coll, c);
            }
        }

        //example call (procedure within a form):
        void bla()
        {
            foreach (TextBox tb in GetControls<TextBox>(this))
            {
                //.....
            }
        }
. . .
posted on Thursday, August 12, 2004 4:20 AM