getting controls by name

  • Thread starter Thread starter Christine Nguyen
  • Start date Start date
C

Christine Nguyen

In VB 6, I believe if you had a control named MyControl on a form named
MyForm, you could obtain a reference to MyControl with a string as in
MyForm.Controls("MyControl"). Is there an equivalent in .NET??

Thanks,
Christine
 
Hello,

Christine Nguyen said:
In VB 6, I believe if you had a control named MyControl on
a form named MyForm, you could obtain a reference to
MyControl with a string as in MyForm.Controls("MyControl").
Is there an equivalent in .NET??

\\\
Private Function FindControl( _
ByVal ControlName As String, _
ByVal CurrentControl As Control _
) As Control
Dim ctr As Control
For Each ctr In CurrentControl.Controls
If ctr.Name = ControlName Then
Return ctr
Else
ctr = FindControl(ControlName, ctr)
If Not ctr Is Nothing Then
Return ctr
End If
End If
Next ctr
End Function
///

Usage:

\\\
DirectCast(FindControl("btnBla", Me), Button).Enabled = False
///

Notice that the procedure listed above is "slow", if you have to access a
lot of controls by name very often, you should store references to them in a
'Hashtable' object. You can use the name of the control as key.
 
Hi Herfried,

Yes I am currently using a Hashtable. I was wondering, however, if there
were any direct implementations built into the framework, but I guess not

Thanks,
Christine
 
Christine,
In addition to Fergus's comments, you could handle the ControlAdded &
ControlRemoved events, then based on these events update the hashtable. If
you have a lot of forms that need this, you could define a new base form
that all your forms inherit from.

I have not used these events, my concern would be they are not raised when
controls are added to control containers such as Group Boxes. You would need
to handle their ControlAdded & ControlRemoved events. With AddHandler &
RemoveHandler this would not be that hard, as you could actually use the
same event handlers in the form to handle all control containers...

Hope this helps
Jay
 
That's a great thought, Jay! Definitely something to consider.

Thanks,
-Christine
 
Hello,

Christine Nguyen said:
Yes I am currently using a Hashtable. I was wondering,
however, if there were any direct implementations built
into the framework, but I guess not

No, not for Windows Forms.
 
Back
Top