簡體   English   中英

如何使用變量來引用文本框?

[英]How can I use a variable to reference a textbox?

我是視覺基礎和編程的新手,但我正在嘗試制作一個統計計數器類型的程序。 我正在嘗試使用變量來引用文本框,例如 k_kills(i) = txtKills(i).Text。 但是,這不起作用,因此我嘗試了以下操作:

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 is Nothing”時都會吐出一個錯誤。

誰能告訴我是否可以完成這項工作?

謝謝。

您將需要在某個集合中找到該控件。 默認情況下,該控件將存在於其父級的Controls 屬性中,並且由於您試圖通過其名稱獲取該控件,因此您可以使用 ControlCollection 的Find 方法 如果您可以保證控件的父級是 Form,那么您可以調用:

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

但是,如果控件的父級可能不是 Form,那么您可以調用:

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

第一個會執行得稍微快一些,因為它只迭代當前 ControlCollection 而第二個可能需要更長的時間,因為如果它在當前 ControlCollection 中找不到控件,那么它也會開始迭代子控件。

在 Mary 發表評論后,我編輯了我的答案以添加這一行 --> 如果 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

假設所有控件都在 Form 中作為父控件,並且它們都以 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM