How to reference a textbox via a string in code?

I imagine that this is a rather simple task; however I do not have a particularly large depth of knowledge and experience in VB…

I have an arrangement of text boxes (id1_1, id1_2, id2_1, id2_2) which I wish to be able to reference in my code from a string such that I can change the text box’s text etc. I receive the data required to construct the string from a connected serial device.

What I require is a method to construct a textbox object reference from a string, something like

getObjRef(string) as object

Cheers
Wilbo



Answer this question

How to reference a textbox via a string in code?

  • ashish1482

    perhaps you could simply iterate through the controls collection of the form until you find the correct control.

    Dim c as control

    for each c in form1.controls

    if c.name="textbox1" then c.text="my new string"

    next c



  • Rania

    This is what I used in the end, JonM was pretty was on the money.

    Thanks guys.

    Cheers
    Wilbo

    -----------------------------------------------------------------------------
            Dim c As Control
            c = rec_find_control("textBox1", Me.Controls)
            If c Is Nothing Then
              'not found
            Else
                c.Text = "FOUND!"
            End If  

         'Returns the contol with the name "str", or nothing if it
        'it was unable to find the control
        Private Function rec_find_control(ByVal str As String, ByVal cc As Object) As Control
            Dim c As Control
            Dim con As Control
            For Each c In cc
                If c.Name = str Then
                    Return c
                End If
                If c.HasChildren() Then
                    con = rec_find_control(str, c.Controls)
                    If con Is Nothing Then
                    Else
                        Return con
                    End If
                End If
            Next c
            Return Nothing
        End Function

  • Humphery

    To do this requires the use of reflection, or if you know the parent form, you can iterate through it's control collection, looking for a control of that name.



  • Pïeter

    Reflection means you can query a class for methods and objects, pretty much in the way you're hoping to. It'

    http://www.developerland.com/DotNet/General/187.aspx

    I've not read this, but a quick scan would suggest it's the best article I found.



  • huseyin_

    Currently I use a select, case statement to select the correct textbox based on the string, I understand that I could iterate through the parent control, however this all seems very inelegant.

    I am hoping there is an elegant solution that I am unaware of :)


    Reflection


    (thanks for your reply by the way)


    Cheers
    Wilbo


  • How to reference a textbox via a string in code?