0

「btn」で始まるボタンの名前をすべてリストしたいのですが、これらのボタンは別のパネルに配置されています。私はこれを心に留めています

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

しかし、私はそれが間違っている可能性があると思います..

4

2 に答える 2

2

まず、最初のパラメータは名前で、2 番目のパラメータはbool再帰的に検索するかどうかを示します。

第二に、これには組み込みの方法がありません。次のような独自の方法を使用します。

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 に答える