This is a common problem faced by many newcomers (and even experienced
devs) to Windows forms. I've answered this kind of question as
recently as December last year :

http://groups.google.co.in/group/DotNetDevelopment/browse_thread/thread/5e072c60f51cce4e
OR
http://tinyurl.com/cnkb6s

The basic problem behind both your question and one I've linked to
remains the same... How to dynamically construct the name of an object
or control on the Form and retrieve a reference to it ?

Well, to elaborate, there are two schools of thought on this matter :

1. Recursively iterate through the Controls collection of the
container to find a control whose name matches the one you want. This
is often considered too slow a method in case you have many controls,
so one way to alleviate the performance issue is to locate the
innermost container control you can and run your iterations *within*
that control. If you have few controls, this is undoubtedly the most
convenient method.

2. Load all the Controls and their names into a Key-Value collection
such as a HashTable. The name will obviously form the Key and the
reference to the Control will be the Value. Collections like the
Hashtable will allow you convenient methods to search within itself.
Of course, this assumes that this loading into the HashTable will be
done on Form initiation and the collection will be accessed later on.
(In another later event, perhaps). Works well even for a large number
of controls in the collection.

If you need more elaboration or details, let me know and I'll post a
code sample of both methods. Or if I'm feeling too lazy, I'll just
post a link. ;-)

Reply via email to