2015-09-08 64 views
1

我想设置一个动态创建的文本框使用变量名的Text属性,但是当我使用Me.Controls(变量名).Text,我得到一个错误说我需要将其设置为“新建”。使用变量的文本框的名称属性在创建时已设置,但我似乎无法使用相同的名称进行检索。VB使用变量名称来访问控件属性

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 
+0

你从哪里得到错误?我无法看到New TextBOx的名称添加到'arrTextVals'的位置。列表或可能是字典(取决于其中的其他信息),可能会更好地工作 – Plutonix

+0

尝试使用DirectCast来获取控件 – Dman

+0

尝试在设置属性后添加控件。 – rheitzman

回答

1

我认为这个问题是在行:

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

来解决这样一个控制正确的方法是,使这样的

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

参考其中i为整数或使用所需控件的名称,在您的情况下可能是

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

当然,我想你提到之前arrTextVals是一个字符串数组

编辑:

你有Me.Controls后一个点(< - 从来没有把一个。在括号之前。