question about VB 2005 express .
is it possible to refer to controls dynamically?
I mean instead of referring to [ textbox1.text] can I have a
mystring = "textbox1"
then refer to the control named in mystring?
Is that possible? What's the syntax for it?
That depends. As Scott says, if you are specifically looking for the
variable name, that would require using reflection.
However, my guess is that you probably don't really want the variable
name. You want the control instance itself. And that you can in fact
get by name.
specifically, I have textboxes named book_1 to book_9
I want to have a loop where I refer to properties of the
textbox named "book_" + str(loop_count)
Assuming you've left the Name property as the default, it should be the
same name as the instance variable referencing the control. So,
assuming "book_1" to "book_9" are valid Name values, you can do
something like this:
Control ctlParent = ...;
for (int itbx = 1; itbx <= 9; itbx++)
{
TextBox tbx;
Control[] rgctl = ctlParent.Find("book_" + itbx.ToString(), true);
tbx = (TextBox)rgctl[0];
// do something with the textbox instance referred to by tbx
}
The above code assumes that you will always find at least one with the
given name. It's also not terribly efficient, being essentially
O(N^2). But for a small number of controls, it should be fine.
That said, if you expect this to be a performance issue, there are
definitely better ways to accomplish the basic behavior you want
without doing exactly the above. It all just depends on the exact
context of what you're doing.
A couple of alternatives:
* Pre-process the search, and save a collection (I'd use
List<TextBox>, but anything would be fine) that you can enumerate at
will later
* Enumerate all the children once, checking each name for matching
against the general pattern, and processing any control that looks like
"book_#" where # is a digit from 1 to 9. You can use Regex or String
class methods to compare the string, and parse the digit to extract the
index so that you can process that particular control according to its
index.
There are lots of other possibilities. It's impossible to say what
would work best for you without more information, but some variation on
the above methods is likely to be suitable.
Pete