Search code examples
c#winformscombobox

ComboBox.DropDownHeight values doesn't change when adding or removing items


When running the following code in a WFA

public partial class Form1 : Form
{
    string[] items = { "A", "B", "C", "D", "E" };

    public Form1()
    {
        InitializeComponent();
        UpdateDropDownHeight();
    }

    private void UpdateDropDownHeight()
    {
        textBox1.Text = comboBox1.DropDownHeight.ToString();
    }

    private void button_populate_Click(object sender, EventArgs e)
    {
        for(int i = 0; i<items.Length; i++)
        {
            comboBox1.Items.Add(items[i]);
        }
        UpdateDropDownHeight();
    }

    private void button_clear_Click(object sender, EventArgs e)
    {
        comboBox1.Items.Clear();
        UpdateDropDownHeight();
    }
}

I have noticed the combobox1.DropDownHeight value never changes when new items are added to the combo box. The apparent drop down area clearly changes when button_populate is clicked through.
Another users question

Combo Box Size Issue After All Items Are Removed

provides a somewhat perplexing answer on how to resize the apparent drop down area after removing items. What then is the purpose of the DropDownHeight property and what is changing the apparent drop down area of the ComboBox?


Solution

  • Also not really sure what problem you're trying to solve, but if you're trying to adjust the height of the DropDownHeight, this can be achieved below.

    private void UpdateDropDownHeight()
    {
        int dropDownHeight = 0;
        for (int i = 0; i <= comboBox1.Items.Count; i++)
        {
            dropDownHeight = dropDownHeight + (comboBox1.ItemHeight);
        }
        comboBox1.DropDownHeight = dropDownHeight;
        textBox1.Text = comboBox1.DropDownHeight.ToString();
    }