About Get All controls in form dynamically

subashbtechmba

Newcomer
Joined
Jun 25, 2009
Messages
3
Hi,

I want to get the controls inside a tab page or group box which is in a windows forms in C#.
Ex:
foreach(Controls ctrl in tabPage1.controls)
{
if(ctrl is Label)
{
my code is here
}
}
Above code is the written by me for accesing Label Controls in my form.But i cant retreive Label Control Because it is inside the tabpage.
Is there any solution for this without specifying Groupbox1.Controls or tabpage1.controls

Plesae help me with the code

Thanks
Subash
 
Hmm.. Shouldn't it work to check in the loop if the ctrl has any controls in it, and then loop through them to? Perhaps create a recursive sub for it or something :)

Just a thought, I might be totally wrong:P hehe
 
As iMP said, you should get something like this:

vb.NET
Code:
Private Function CheckControls(ByVal control As Control) As Control
        For Each c As Control In control.Controls
            If c.Controls.Count > 0 Then CheckControls(c)
            If TypeOf c Is Label Then
' Do something with c
                Return c
            End If
        Next
        Return Nothing
    End Function

or C#
Code:
private Control CheckControls(Control control)
{
    foreach (Control c in control.Controls) {
        if (c.Controls.Count > 0) CheckControls(c); 
        if (c is Label) {
            // Do something with c
            return c;
        }
    }
    return null;
}

~DP
 
Back
Top