无法从Winforms组合框中完全清除项目

时间:2015-06-30 19:06:01

标签: vb.net winforms combobox

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

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

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

  3. 然而,组合框下拉区域保留了已填充的行,除了它们是空的"。换句话说,它是一个白色的盒子,与它所包含的列表的高度相同。

    对我来说,如果我清除一个ComboBox,它应该看起来与从未被绑定或填充的那个相同。

    DropDownStyle = DropDownList

    填充/绑定前的

    ComboBox:

    ComboBox before filling/binding

    填充/绑定后

    ComboBox:

    ComboBox after filling/binding

    清除/设置datasource / bindingsource后的ComboBox = Nothing:

    ComboBox after clearing/setting datasource/bindingsource = Nothing

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

    感谢。

3 个答案:

答案 0 :(得分:2)

The following should fix that:

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

For some reason changing the 'DropDownStyle' property of the combobox to something that is not DropDownList, and then changing it back resizes the DropDownList to the minimum possible height for its entries, or at least in Visual Studio 2015 with .NET Framework 4.5. Hope this helps.

Edit: It's strange that if the ComboBox's style is ComboBoxStyle.DropDown that ComboBox.DropDownHeight = 106 will change the height, but if the style is ComboBoxStyle.DropDownList it won't. Yet another mystery of .NET!

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

You must set the DropDownHeight property of the ComboBox control after clearing the DataSource. Here is an example that sets it back to a default that you can adapt for your own purposes.

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