创建现有按钮阵列vb 2013

时间:2014-12-23 18:37:43

标签: arrays vb.net

我曾经在VB6中编程,并且我正在尝试在VB 2013中编写相同的程序。在这个程序中,我使用了49个按钮的数组,当你点击它们时它们都做同样的事情。我已经想到必须点击功能到一点:

Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button9.Click, Button10.Click, Button11.Click, Button12.Click, Button13.Click, Button16.Click, Button17.Click, Button18.Click, Button19.Click, Button20.Click
   ...

End Sub

我想要做的是将代码简化为使用数组,以便我可以传递索引。另一个人在2010年问了同样的问题,最好的答案是:

Button[] array = { firstButton, secondButton };

那会有效,但我想要一些打字少的东西。我也尝试了以下失败:

Button[] buttons = this.Controls.OfType<Button>().ToArray();

两个

For i = 1 To 100
  Dim btns() As Button = Controls.Find("Button" & i, True)
  Dim btn As Button
  If btns IsNot Nothing Then
    btn = btns(0)
    'If buttons Is Nothing Then
    '  ReDim buttons(0)
    'Else
    '  ReDim Preserve buttons(buttons.Length)
    'End If
    'buttons(UBound(buttons)) = btn
    btn.Text = i - 1 'here you can change whatever you want
  End If
Next

Dim buttons() As Button

buttons = Nothing
For Each b As Button In Me.Controls
If buttons Is Nothing Then
    ReDim buttons(0)
Else
    ReDim Preserve buttons(buttons.Length)
End If
buttons(UBound(buttons)) = b
Next

我无法接受将现有按钮接受到数组中。我希望有人可以提供帮助。

2 个答案:

答案 0 :(得分:1)

如果您的Button嵌套在容器控件中(例如GroupBox),则需要对所有按钮执行递归搜索。也许这样的事情(完全没有优化)......

Private Function FindAllButtons(root As Control) As List(Of Button)
    Dim result As List(Of Button) = New List(Of Button)()
    For Each c As Control In root.Controls
        If TypeOf c Is Button Then
            result.Add(DirectCast(c, Button))
        ElseIf c.HasChildren Then
            result.AddRange(FindAllButtons(c))
        End If
    Next
    Return result
End Function

然后在Form

中调用它
Dim allButtons as List(Of Button) = FindAllButtons(Me)
' Add common Click handler
For Each b As Button In allButtons
    AddHandler b.Click, AddressOf Button_Click
Next

更新只是为了好玩,这是一个通用版本,可以找到其他类型的控件。

Private Function FindAllControls(Of T As Control)(root As Control) As List(Of T)
    Dim result As List(Of T) = New List(Of T)()
    For Each c As Control In root.Controls
        If TypeOf c Is T Then
            result.Add(DirectCast(c, T))
        ElseIf c.HasChildren Then
            result.AddRange(FindAllControls(Of T)(c))
        End If
    Next
    Return result
End Function

你可以使用它:

Dim allButtons As List(Of Button) = FindAllControls(Of Button)(Me)
Dim allTextBoxes As List(Of TextBox) = FindAllControls(Of TextBox)(Me)

答案 1 :(得分:0)

选项二将起作用,您只需要将找到的按钮添加到列表中。我建议你将按钮添加到List(Of)而不是数组中。如果确实需要,您可以随时将列表转换为数组。

    Dim buttonList As New List(Of Button)

    For i As Integer = 1 To 100
        Dim btns() As Control = Controls.Find("Button" & i, True)

        If btns IsNot Nothing AndAlso btns.Length > 0 Then
            buttonList.Add(CType(btns(0), Button))
        End If
    Next