【问题标题】:Clear/Deselect ComboBox control(s) within GroupBox control清除/取消选择 GroupBox 控件中的 ComboBox 控件
【发布时间】:2015-01-03 07:44:50
【问题描述】:

我的问题:

我有一个功能可以清除组框中的文本框和组合框 (DropDownList)。虽然文本框正在清除,但我无法清除组合框。

我的代码:

Public Sub ClearGroupControls()
    For Each groupboxControl As Control In Me.Controls
        If TypeOf groupboxControl Is GroupBox Then
            For Each control As Control In groupboxControl.Controls
                ' Clear controls
                If TypeOf control Is TextBox Then
                    control.Text = ""
                ElseIf TypeOf control Is ComboBox Then
                    'control.Text = String.Empty
                    'control.SelectedIndex = -1
                    control.Text = ""
                End If
            Next
        End If
    Next
End Sub

注意:.SelectedIndex = -1 产生错误:

SelectedIndex 不是 System.Windows.Forms.Control 的成员

...考虑到 control.Text 在控件是 TextBox 时有效。

【问题讨论】:

  • 这些组合的 DropDownStyle 是什么?
  • @Steve DropDownList.

标签: vb.net visual-studio winforms combobox


【解决方案1】:

循环遍历控件集合会返回一个没有 SelectedIndex 属性的通用控件。
您需要将其转换为适当的类型

Public Sub ClearGroupControls()
    For Each groupboxControl In Me.Controls.OfType(Of GroupBox)()
        For Each control As Control In groupboxControl.Controls
            ' Clear controls
            If TypeOf control Is TextBox Then
                control.Text = ""
            ElseIf TypeOf control Is ComboBox Then
                Dim cbo = DirectCast(control, ComboBox)
                cbo.SelectedIndex = -1
            End If
        Next
    Next
End Sub

请注意,在外部循环中,您可以使用 IEnumerable 扩展来仅需要 Form 的 Controls 集合中的枚举器返回的 GroupBox 类型的控件。

您可以将内部循环更改为两个循环以利用 OfType 扩展,但如果它确实提供了更好的性能,则应进行测量(这在很大程度上取决于您的组合框中存在的控件数量)

Public Sub ClearGroupControls()
    For Each groupboxControl In Me.Controls.OfType(Of GroupBox)()
        For Each txt In groupboxControl.Controls.OfType(Of TextBox)()
            txt.Text = ""
        Next
        For Each cbo In groupboxControl.Controls.OfType(Of ComboBox)()
           cbo.SelectedIndex = -1
        Next
    Next
End Sub

【讨论】:

  • 它可以工作,但我不明白你建议我可以用 IEnumerable 实现什么。我研究了official overview"simplified" (as in, not at all) overview 但无济于事。最终,你是说它会取代内部循环,此外,你会耐心/友善地指导我如何做吗?
  • 好吧,我没有权力比发布的两个链接更好地解释,但我认为OfType 扩展就像一个应用于 Controls 序列的过滤器,它只允许括号中指示的类型的对象到达你的 groupboxControl 变量。通过这种方式,您可以避免演员表。控件变量 groupboxControl 不再是通用控件,而是具有特定属性的特定 GroupBox 控件
  • 在内部循环中,您需要检查两种不同类型的控件,因此不可能有一个循环 OfType(????)。您可以编写两个循环,一个用于 TextBoxes,一个用于 ComboBoxes,但我认为您一无所获。所以路线是要有一个通用控件,在 Is return true 之后将其转换为 ComboBox
  • 感谢您分解它。我最终使用了一个依赖于TryCast() 并允许将父级指定为参数的递归方法(顺便说一下,允许.SelectedIndex = -1)。 Working code 通过 PasteBin。
猜你喜欢
  • 2011-07-11
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 2019-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多