0

我想列出以“btn”开头的所有按钮名称,但这些按钮位于不同的面板中。我心里有这个

dim obj() as object in frmForm.Controls.Find(True,"btn*")

但我认为这可能是错误的..

4

2 回答 2

2

首先,第一个参数是名称,第二个参数 abool表示是否要递归搜索。

其次,没有内置的方法。我会使用您自己的方法,如下所示:

Public Function FindControlStartsWith(root As Control, name As String, recursive As Boolean, comparison As StringComparison) As Control()
    If root Is Nothing Then
        Throw New ArgumentNullException("root")
    End If
    Dim controls = New List(Of Control)
    Dim stack = New Stack(Of Control)()
    stack.Push(root)

    While stack.Count > 0
        Dim c As Control = stack.Pop()
        If c.Name.StartsWith(name, comparison) Then
            controls.Add(c)
        End If
        If recursive Then
            For Each child As Control In root.Controls
                stack.Push(child)
            Next
        End If
    End While
    Return controls.ToArray()
End Function

以这种方式使用它:

Dim obj() As Control = FindControlStartsWith(Me, "BUT", True, StringComparison.OrdinalIgnoreCase)
于 2013-10-10T10:01:42.780 回答
1

我对控件的类型做了类似的事情,但是可以很容易地修改它的名称。试试下面的代码:

Private Sub findcontrols(ByVal root As Control)

    For Each cntrl As Control In root.Controls
        findcontrols(cntrl)
        If cntrl.name.startswith("btn") Then
            msgbox(cntrl.name)
        End If


End Sub

您可以通过为控制递归等内容添加参数来使其更加复杂。请记住,如果您想使用它执行任何特定于控件类型的操作(即,控件中未从 Control 类继承的任何内容),您需要将该对象 CType 为适当的控件。因此,如果 .name 仅在 Button 类中,并且在 Control 类中不存在,则我必须执行以下操作才能使其正常工作:

msgbox(ctype(cntrl, Button).name)

我自己的个人版本看起来更像这样:

Private Sub clearcontrols(ByVal root As Control, ByVal ClearLists As Boolean, Optional ByVal ClearTabPages As Boolean = False)
    For Each cntrl As Control In root.Controls
        clearcontrols(cntrl, ClearLists, ClearTabPages)

        If TypeOf cntrl Is TextBox  Then
            CType(cntrl, TextBox).Clear()
        End If

        If TypeOf cntrl Is DataGridView Then
                CType(cntrl, DataGridView).Rows.Clear()
        End If

        If TypeOf cntrl Is ListBox   And ClearLists = True Then
                CType(cntrl, ListBox).Items.Clear()
        End If

        If TypeOf cntrl Is TabControl And ClearTabPages = True Then
            For Each tp As TabPage In CType(cntrl, TabControl).TabPages
                If DynTPList.Contains(tp.Name) Then
                    tp.Dispose()

                End If

            Next
        End If
    Next

End Sub
于 2013-10-11T16:25:39.403 回答