July 21st, 2003, 02:14 PM
-
Locating Controls Within A Form
Suppose there is a form named fMain. Within fMain you have dynamically created some controls. You determine that you need to check and see at a given time if a specific control exists.
If I hardcode a control name, as shown below, everything works fine. If I attempt to dynamically provide a control name (as from a string), the system bombs. (I have listed a couple of variations of my bombed code for your amusement.) I understand why my examples that do not work. I simply tried them because I am desperate to find something that does work.
For my application, I really need to be able to dynamically select the names of my controls. Hardcoding really will not work for me.
Any ideas?
WORKING CODE
if (this.Controls.Contains(txtMain))
{
// .... Do Something
}
NON-WORKING CODE
string name="";
name="txtMain";l
if (this.Controls.Contains(name))
{// Do Something}
OR
string name="";
name="txtMain";l
if (this.Controls.Contains( (TextBox) name))
{// Do Something}
string name="";
name="txtMain";l
On a related note, I would like to be able to set an instance of a control equal to one of my dynamically created controls. I can't figure out how to pass the instance name as a string to any method that will retrieve the control
TextBox oTextBox=???? name
July 21st, 2003, 05:41 PM
-
I'm not sure why you wouldn't just use a reference to the control as opposed to the controls name.
Anyways, every control contains a 'Name' property so why not just loop through all the controls yourself checking the 'Name' property until you find the one you want?
July 22nd, 2003, 09:09 PM
-
It is certainly possible to loop through the names but very inefficient. However, this is the solution that I had come up with and have not found any other. So, for now, I guess this is the way I will go.
Thank you for your help!