VB.NET - 如何将控件名称与另一个变量值连接起来以更改其属性?

VB.NET - How do i concatenate a Control name with another variable value to change it's properties?

我想更改“with”中引用的文本框的属性(示例:ReadOnly、BorderStyle、Forecolor...)。

Private Sub Apply(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txt10.KeyDown, txt0.KeyDown

   If txt10.ReadOnly = False Then
      If e.KeyCode = Keys.Enter Then

         With txt10
         .ForeColor = Color.White
         .ReadOnly = True
         .BorderStyle = BorderStyle.None
         End With

      End If
   End If
End Sub

问题是,我需要将这些属性设置到某个文本框,所以我声明了一个名为“Number”的变量,我在想这是否可行:

With Controls("txt" & Number)
         .ForeColor = Color.White
         .ReadOnly = True
         .BorderStyle = BorderStyle.None
         End With

这仅适用于某些属性,不适用于“with”。您知道如何进行这项工作吗?

检索控件并将其定义为文本框。然后像以前一样使用它。当您从 Controls 集合中获取控件时,由于未指定控件类型,某些属性将不可用(例如文本框只读 属性)。

Dim textBox As TextBox = DirectCast(Controls("txt" & number), TextBox)

If textBox.ReadOnly = False AndAlso e.KeyCode = Keys.Enter Then
    With textBox
        .ForeColor = Color.White
        .ReadOnly = True
        .BorderStyle = BorderStyle.None
    End With
End If