Ross from Brooklin
Ross from Brooklin

Reputation: 303

VB Using variable name to access control properties

I am trying to set the Text property of a dynamically created text box using a variable name, but when I use the Me.Controls(variable name).Text, I'm getting an error saying I need to set it up as "New". The name property of the text box, using a variable, was set when it was created but I don't seem to be able to retrieve using the same name.

    Private Sub Example(panposition As Integer)

    Dim tbfile = New TextBox()
    Dim lineExample As Integer = 2
    ' creating a text box with a variable name
    Controls.Add(tbfile)                    ' create the new textbox to hold the file name
    tbfile.Name = "tbfile" + panposition.ToString
    tbfile.Location = New Point(85, tvposition)
    tbfile.Size = New Size(155, 20)
    tbfile.Text = "file name"
    tbfile.TextAlign = HorizontalAlignment.Left
    tbfile.HideSelection = False
    tbfile.TabStop = False
    tbfile.AllowDrop = False
    tbfile.Visible = True

    ' trying to update the text in the text box using file name and text retrieved from an array
    Me.Controls.(arrTextVals(1, lineExample)).Text = arrTextVals(2, lineExample)


End Sub

Upvotes: 1

Views: 1420

Answers (1)

mago
mago

Reputation: 56

I think the problem is in line:

Me.Controls.(arrTextVals(1, lineExample)).Text = arrTextVals(2, lineExample)

The correct way to address a control in this way is to make a reference like this

Me.Controls(i).Text = arrTextVals(2, lineExample)

where i is an integer or using the name of the desired control which in your case could be

Me.Controls(arrTextVals(1, lineExample)).Text = arrTextVals(2, lineExample)

Of course i suppose as you mentioned before that arrTextVals is a string array

Edit:

You have a dot after Me.Controls.( <- never put a . before a bracket.

Upvotes: 1

Related Questions