How to identify controls in a collection

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all,

I have a user control that has a button and five labels. Using foreach to
loop through all the controls, how do I identify all the labels apart from
the button?
 
For Each Ctrl As Control In UserControl.Controls
If TypeOf Ctrl Is Button Then
' its a button
ElseIf TypeOf Ctrl Is Label Then
' its a label
ElseIf TypeOf Ctrl Is TextBox Then
' its a textbox
...
End If
Next Ctrl

hope that helps..
Imran.
 
Amil said:
I have a user control that has a button and five labels.
Using foreach to loop through all the controls, how do
I identify all the labels apart from
the button?

\\\
if (foo is Label)
...;
else if (foo is Button)
...;
///
 
How can I loop thru the controls in my usercontrol? My usercontrol adds a
label everytime you click on the button and there can be none of more than
one labels. Using foreach requires that the collection is of the same type.
 
Amil said:
How can I loop thru the controls in my usercontrol? My
usercontrol adds a label everytime you click on the button
and there can be none of more than one labels. Using
foreach requires that the collection is of the same type.

If you are not nesting controls, you can use this code:

\\\
foreach (Control c in this.Controls)
{
if (c is Label)
{
Label cc = (Label)c;
...;
}
else if (c is Button)
...;
}
///

If you set the controls' names, you can uniquely identify the controls...
 
Thanks Herfried. It works.

Herfried K. Wagner said:
If you are not nesting controls, you can use this code:

\\\
foreach (Control c in this.Controls)
{
if (c is Label)
{
Label cc = (Label)c;
...;
}
else if (c is Button)
...;
}
///

If you set the controls' names, you can uniquely identify the controls...
 
Back
Top