Jan Tacci
Jan Tacci

Reputation: 3211

Combo Box Size Issue After All Items Are Removed

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:

Combo Box Initial

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:

Combo Box Reduced

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:

Combo Box Cleared

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:

Combo Box Initial No Data

Any ideas as to why this is happening?

Upvotes: 6

Views: 4173

Answers (4)

user1800738
user1800738

Reputation: 167

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("");

Upvotes: 4

Luke
Luke

Reputation: 513

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; 

Upvotes: 6

mehdi
mehdi

Reputation: 685

set DropDownHeight property to fix size

 versionComboBox.DropDownHeight = 106; // default value

Upvotes: 0

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15148

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).

Upvotes: 1

Related Questions