清除/取消选择GroupBox控件中的ComboBox控件

时间:2014-11-06 17:26:15

标签: vb.net winforms visual-studio combobox clear

我的问题:

我有一个功能来清除组框内的文本框和组合框(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时,它似乎不一致。

1 个答案:

答案 0 :(得分:2)

循环控件集合将返回一个没有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