无法完全清除 Winforms ComboBox 中的项目

Cannot Fully Clear the Items from a Winforms ComboBox

标题有点误导。我可以通过通常的方法将 .Items 计数减少到零,但下拉列表区域保持其以前的尺寸。

  1. 手动添加项目到ComboBox时,我可以做到ComboBox.Items.Clear。 ComboBox.Items 计数减少为零。

  2. 当数据绑定 ComboBox 时,我可以做 ComboBox.DataSource = Nothing。或者,如果使用一个,则设置 BindingSource = Nothing。 ComboBox.Items 计数减少为零。

但是,组合框下拉区域保留了它填充的行,除了它们是 "empty"。换句话说,它是一个白框,其高度与其包含的列表相同。

在我看来,如果我清除组合框,它应该看起来与从未绑定或填充的组合框相同。

DropDownStyle = DropDownList

组合框在filling/binding之前:

组合框在filling/binding之后:

ComboBox 在 clearing/setting datasource/bindingsource = Nothing 之后:

有谁知道防止这种情况发生的方法吗?如果我取消绑定或以其他方式清除 ComboBox,我希望下拉菜单包含一个空行,如第一张图片所示。

谢谢。

您必须在清除 DataSource 后设置 ComboBox 控件的 DropDownHeight 属性。这是一个将其设置回默认值的示例,您可以根据自己的目的进行调整。

Private m_intDefaultDropDownHeight As Integer = 1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim lstItems As New List(Of String)

    lstItems.Add("A")
    lstItems.Add("B")
    lstItems.Add("C")

    m_intDefaultDropDownHeight = ComboBox1.DropDownHeight

    ComboBox1.DataSource = lstItems

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ComboBox1.DataSource = Nothing
    ComboBox1.DropDownHeight = m_intDefaultDropDownHeight
End Sub

以下应该解决这个问题:

ComboBox.DropDownStyle = ComboBoxStyle.DropDown
ComboBox.DropDownStyle = ComboBoxStyle.DropDownList

出于某种原因,将组合框的 'DropDownStyle' 属性 更改为非 DropDownList 的内容,然后将其改回会将 DropDownList 的大小调整为其条目的最小可能高度,或者至少在 Visual Studio 2015 年使用 .NET Framework 4.5。希望这有帮助。

编辑:奇怪的是,如果 ComboBox 的样式为 ComboBoxStyle.DropDown,则 ComboBox.DropDownHeight = 106 会改变高度,但如果样式为 ComboBoxStyle.DropDownList,则不会。 .NET 的又一谜团!

要强制重置下拉元素的高度,您需要将 ComboBox.DropDownStyle 更改为其他元素并返回原始高度

Me.ComboBox1.DataSource = Nothing
Me.ComboBox1.DropDownStyle = ComboBoxStyle.DropDown
Me.ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList