Combo Box Size Issue After All Items Are Removed

泪湿孤枕 提交于 2019-12-19 08:12:13

问题


My application contains a ComboBox that the user can delete items from. When the program starts up it populates the ComboBox from a list of strings read in from a configuration file.

Here is the code to add items:

// version list is an array of strings
foreach (string version in versionList)
{
  versionComboBox.Items.Add(version);
}
if (versionComboBox.Items.Count > 0)
{
    versionComboBox.SelectedIndex = 0;
}

Here is a screenshot of the combo box after it's been populated:

If the user clicks the Delete button the program removes the selected item from the ComboBox using the following code:

if (versionComboBox.SelectedIndex >= 0)
{
    versionComboBox.Items.Remove(versionComboBox.SelectedItem);
}
if (versionComboBox.Items.Count > 0)
{
    versionComboBox.SelectedIndex = 0;
}

Here is a screenshot of the combo box after a few items have been removed:

The problem I am having is when the last item is removed the ComboBox resizes itself to the size it was when it was initially populated. There aren't any items in the ComboBox but it sizes itself as if there were.

Here is a screenshot after all the items have been removed:

As you can see the size is too big. I would think that after all the items were cleared it would look like the following:

Any ideas as to why this is happening?


回答1:


To clear your combo box you can add this:

if (versionComboBox.Items.Count == 0)
{
    versionComboBox.Text = string.Empty;
    versionComboBox.Items.Clear();
    versionComboBox.SelectedIndex = -1;
}

Another approach is to manipulate the items in the data source and rebind the control each time (a lot less for you to worry about).




回答2:


Try to use this at the end of your code when you are filling the combobox items:

comboBoxNumTreno.IntegralHeight = true; // auto fit dropdown list

Then to clear it up:

comboBoxNumTreno.ResetText();
comboBoxNumTreno.Items.Clear();
comboBoxNumTreno.SelectedIndex = -1;
comboBoxNumTreno.DropDownHeight = 106; // default value
comboBoxNumTreno.IntegralHeight = false; 



回答3:


I know this is an old post, but it took me a long time to figure this out and I wanted to let anyone in the future know. After you clear your combo box just do a blank add items and it resets the height.

comboBox1.Items.Clear();
comboBox1.Items.Add("");



回答4:


set DropDownHeight property to fix size

 versionComboBox.DropDownHeight = 106; // default value


来源:https://stackoverflow.com/questions/17769148/combo-box-size-issue-after-all-items-are-removed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!