如何使用变量引用文本框?



我是Visual Basic和编程的新手,但我正在尝试制作一种统计计数器类型的程序。我尝试使用变量来引用文本框,例如,k_kills(i( = txtKills(i(。发短信。但是,这不起作用,因此我随后尝试了以下方法:

For i = 0 To 8
Dim tempBox As TextBox
Dim tempName As String = "txtKills" & i.ToString
tempBox = Me.Controls.Item(tempName)
k_kills(i) = tempBox.Text
Next

这也不起作用,并且每次都会吐出一个错误,说"tempBox 是什么都没有"。

谁能告诉我我是否可以完成这项工作?

谢谢。

您需要在某个集合中找到控件。默认情况下,该控件将存在于其父级的 Controls 属性中,并且由于您尝试按其名称获取控件,因此您可以使用 ControlCollection 的 Find 方法。如果可以保证控件的父项是窗体,则可以调用:

Dim tempBox As TextBox = DirectCast(Me.Controls.Find(tempName, False), TextBox)

但是,如果控件的父控件的父级可能不是窗体,则可以调用:

Dim tempBox As TextBox = DirectCast(Me.Controls.Find(tempName, True), TextBox)

第一个执行速度稍快,因为它只循环访问当前 ControlCollection,而第二个可能需要更长的时间,因为如果它在当前 ControlCollection 中找不到控件,则它也开始迭代子控件。

假设控件都作为父控件在窗体中,并且它们都以 txtKills 开头...... 如果要将这些文本框作为一个组用于多个操作,则可能需要生成 TextBox 的数组或列表。

Dim Kills(7) As TextBox
Private Sub CreateTextBoxArray()
Dim index As Integer
For Each ctrl As Control In Controls
If ctrl.Name.StartsWith("txtKills") Then
Kills(index) = DirectCast(ctrl, TextBox)
index += 1
End If
Next
End Sub
Private Sub ClearKillTextBoxes()
For Each t In Kills
t.Clear()
Next
End Sub
Private Function GetTextFromKillBoxes() As List(Of String)
Dim lst As New List(Of String)
For Each t In Kills
lst.Add(t.Text)
Next
Return lst
End Function

在玛丽的评论之后,我编辑我的答案以添加这一行 --> 如果 Option Strict 为 On 且 'For' 以 0 或 1 或任何数字开头且 txtKills[X] 存在,我的代码不起作用。

这是我之前的答案,我不知道我是否必须删除:

您的代码工作正常,但我认为您有一个错误,因为您的 For 以 0 开头,并且您没有任何"txtKills0"。我现在已经测试过了:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim k_kills(10) As String '<< Ignore the length
For i = 1 To 7
Dim tempBox As TextBox
Dim tempName As String = "txtKills" & i.ToString
tempBox = Me.Controls.Item(tempName)
k_kills(i) = tempBox.Text
MsgBox(k_kills(i))
Next
End Sub

最新更新