"Tamarack" <(E-Mail Removed)> schrieb
> I have a simple function which loops through all the controls on a
> form searching for a specific one:
>
> Public Function FindControl(ByVal ctrls As
> Control.ControlCollection,
> ByVal ctrlName As String) As Control
>
> For Each ctrl As Control In ctrls
> If ctrl.Name = ctrlName.Trim Then
> Return ctrl
> End If
> If ctrl.HasChildren Then
> FindControl(ctrl.Controls, ctrlName)
> End If
> Next
> Return Nothing
> End Function
>
> But how do I reference that control's properties simply by knowing
> it's name? The results of the looping function above allows me to
> work with a strongly typed object so I can directly reference the
> properties because it finds the object given the name. But it is
> extremely inefficient. What I'm trying to do is exactly what you can
> do with an ADO recordset where you refer to a specific field by it's
> name:
>
> myRecordset("txtFirstName") = "Robert"
>
> I would like to do the same thing with the Controls collection of a
> given form:
>
> myForm.Controls("txtFirstName").Text = "Robert"
>
> Of course this is not allowed in .Net but I'm trying to find the
> equivalent. Basically, I need to refer to a control directly by using
> its name instead of looping through all the controls to find one that
> matches the name I already know.
>
> I know it's a little confusing and I'm probably not explaining it
> very well, but thanks for any assistance.
You explained it very well.
First, /why/ do you need the name? Names are used at design time as
expressive names for the programmer and are resolved at compile time but
shouldn't matter at runtime. The compiler can not find misspelled names
placed in Strings. You'd get a runtime error.
Despite: you could use a modified version of the loop above and add each
found control to a Hashtable. The items in the Hashtable (= the controls)
can be accessed by their names. The loop can run once.
--
Armin
How to quote and why:
http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html