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:
The Items property is used to add and access items in a ComboBox.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With