【问题标题】:Get all combobox names VB.NET获取所有组合框名称 VB.NET
【发布时间】:2017-12-20 18:06:05
【问题描述】:

我正在尝试遍历我的 windows 窗体 VB.net 应用程序上的所有组合框。

我以为这会奏效

Array.ForEach(Me.Controls.OfType(Of ComboBox).Items.Add(DataGridView1.Columns(i).Name)))

但我无法参考当时似乎不知道它是一个组合的项目

我正在尝试获取所有组合框名称的列表,因此我希望可以在循环中使用该名称列表来添加项目并读取所选索引,但我的名称列表始终为空白。我正在使用以下代码,只是试图将列表发送到一个消息框,看看它是否在抓取任何名称。

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim allComboBoxValues As String = ""
    Dim c As Control
    Dim childc As Control
    For Each c In Me.Controls
        For Each childc In c.Controls
            If TypeOf childc Is ComboBox Then
                allComboBoxValues &= CType(childc, ComboBox).Text & ","
            End If
        Next
    Next
    MsgBox(allComboBoxValues)

    If allComboBoxValues <> "" Then
        MsgBox(allComboBoxValues)
    End If
End Sub

【问题讨论】:

  • 你可以只创建一个 CBO 数组,这样你就不必每次都去寻找它们
  • 组合、面板、网格视图的容器是什么?
  • 你可以有多个深度的容器,所以如果没有递归,我认为这个解决方案是行不通的。当前发布的答案是我认为最干净的。

标签: vb.net winforms combobox


【解决方案1】:

下面的function可以用来检索某个类型的所有子Controls

Private Function GetAll(Control As Control, Type As Type) As IEnumerable(Of Control)
        Dim Controls = Control.Controls.Cast(Of Control)()
        Return Controls.SelectMany(Function(x) GetAll(x, Type)).Concat(Controls).Where(Function(y) y.GetType = Type)
End Function

用法:

GetAll(Me, GetType(Combobox))

满足您的需求:

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim Values As String = String.Empty
    For Each ComboBox As ComboBox In GetAll(Me, GetType(ComboBox))
        Values &= ComboBox.Text & ","
    Next
    MsgBox(Values)
End Sub

(Function retrieved from this answer and converted to vb.net)

【讨论】:

    【解决方案2】:

    我使用这种扩展方法。它使用非常干净的泛型。在 cmets 中提到,递归是必须的。

    Public Module ExtensionMethods
    
        <Extension()>
        Public Function ChildControls(Of T As Control)(ByVal parent As Control) As IEnumerable(Of T)
            Dim result As New List(Of T)
            For Each ctrl As Control In parent.Controls
                If TypeOf ctrl Is T Then result.Add(CType(ctrl, T))
                result.AddRange(ctrl.ChildControls(Of T)())
            Next
            Return result
        End Function
    
    End Module
    

    在您的场景中使用:

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim myCombos = Me.ChildControls(Of ComboBox)
        Dim allComboBoxValues = String.Join(", ", myCombos.Select(Function(c) c.Text))
        If myCombos.Any() Then
            MsgBox(allComboBoxValues)
        End If
    End Sub
    

    【讨论】:

    • 感谢您的帮助!这种方式将有助于此应用程序的其他部分。
    猜你喜欢
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多