使用变量访问按钮名称

问题描述:

在visual basic中,我希望能够使用存储在变量中的数字访问按钮的名称。 例如,如果我有24个按钮,它们都被命名为'按钮',其后面的数字为1,2,3 ... 22,23,24。如果我想改变前八个按钮中的文字,我会怎么做。使用变量访问按钮名称

这里是我的例子来帮助说明我的意思:

For i = 1 to 8 
     Button(i).text = "Hello" 
    Next 
+0

的可能的复制[如何创建VB .NET控件数组(HTTP:/ /stackoverflow.com/questions/5299435/how-to-create-control-arrays-in-vb-net) – Jaxedin

+0

检查[此答案](http://stackoverflow.com/a/41412984/4934172) –

For index As Integer = 1 To 8 
    CType(Me.Controls("Button" & index.ToString().Trim()),Button).Text = "Hello" 
Next 

使用LINQ,你是好去:

Dim yourButtonArray = yourForm.Controls.OfType(of Button).ToArray 
' takes all controls whose Type is Button 
For each button in yourButtonArray.Take(8) 
    button.Text = "Hello" 
Next 

或者

Dim yourButtonArray = yourForm.Controls.Cast(of Control).Where(
    Function(b) b.Name.StartsWith("Button") 
    ).ToArray 
' takes all controls whose name starts with "Button" regardless of its type 
For each button in yourButtonArray.Take(8) 
    button.Text = "Hello" 
Next 

在任何情况下, .Take(8)将重复存储在里面的前8个项目yourButtonArray

我希望它有帮助。

提出的解决方案,如果按钮没有直接包含由窗体本身到目前为止将会失败。如果他们在不同的容器中呢?例如,您可以简单地将“我”更改为“面板1”,但如果按钮分布在多个容器多个容器上,则不起作用。

要使其工作,无论是按键位置,使用Controls.Find()方法与“searchAllChildren”选项:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Dim ctlName As String 
    Dim matches() As Control 
    For i As Integer = 1 To 8 
     ctlName = "Button" & i 
     matches = Me.Controls.Find(ctlName, True) 
     If matches.Length > 0 AndAlso TypeOf matches(0) Is Button Then 
      Dim btn As Button = DirectCast(matches(0), Button) 
      btn.Text = "Hello #" & i 
     End If 
    Next 
End Sub