Live Chat Icon For mobile
Live Chat Icon

How do I set the width of a combobox to fit the entries in its list

Platform: WinForms| Category: ComboBox

You can iterate through the list to find the longest text extent using MeasureString, and then use this as the combobox width adding a fudge factor for the dropdown button.

	System.Drawing.Graphics g = comboBox1.CreateGraphics();
	float maxWidth = 0f;
	foreach(object o in comboBox1.Items)
	{
		float w = g.MeasureString(o.ToString(), comboBox1.Font).Width;
		if(w > maxWidth)
			maxWidth = w;
	}
	g.Dispose();
	comboBox1.Width = (int) maxWidth + 20; // 20 is to take care of button width

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.