Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

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

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 drop-down button.

using ( 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;
  }
}
comboBox1.Width = (int) maxWidth + 20; // 20 is to take care of button width

Contributed from George Shepherd's Windows Forms FAQ



Page view counter