#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    8
    Rep Power
    0

    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
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Posts
    109
    Rep Power
    12
    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?
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    8
    Rep Power
    0
    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!

IMN logo majestic logo threadwatch logo seochat tools logo