Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComboBox.MaxDopDownItems is not working when adding items using the Click event

I am populating the ComboBox items with a list using the Click event. When it is already populated the MaxDropDownItems is not working. Does anyone know how to fix this one?

Here's the code:

    List<string> list = new List<string>();
    ComboBox cb;
    private void button1_Click(object sender, EventArgs e)
    {
       cb = new ComboBox();

        cb.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
        cb.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
        cb.FormattingEnabled = true;
        cb.Size = new System.Drawing.Size(94, 21);
        cb.MaxDropDownItems = 5;
        cb.Click +=new EventHandler(cb_Click);

        this.Controls.Add(cb);
    }

    private void cb_Click(object sender, EventArgs e) 
    {
        foreach (string str in list)
        {
            cb.Items.Add(str);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        list.Add("1");list.Add("2");list.Add("3");
        list.Add("4");list.Add("5");list.Add("6");
        list.Add("7");
    }

MaxDropDownItems is set to 5 so the combobox should atleast show 5 items only: alt text

like image 805
Rye Avatar asked Oct 06 '10 01:10

Rye


People also ask

Which property is used to add and access items in a ComboBox?

The Items property is used to add and access items in a ComboBox.

How do I make my ComboBox non editable?

To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this: stateComboBox.


1 Answers

You need to set the ComboBox.IntegralHeight property to false when you setup your control (it defaults to true). From MSDN:

When this property is set to true, the control automatically resizes to ensure that an item is not partially displayed. If you want to maintain the original size of the ComboBox based on the space requirements of your form, set this property to false.

Add this line before you add the combobox to the Controls collection:

cb.IntegralHeight = false;
like image 60
Ahmad Mageed Avatar answered Oct 14 '22 16:10

Ahmad Mageed