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 ListBox to fit the text?

You can iterate through the list to find the longest text extent using MeasureString, adding a fudge factor if the is present.

using ( System.Drawing.Graphics g = listBox1.CreateGraphics() )
{
  float maxWidth = 0f;
  float height = 0f;
  for ( int i = 0; i < listBox1.Items.Count; ++i )
  {
    float w = g.MeasureString( listBox1.Items[ i ].ToString(), listBox1.Font ).Width;
    if ( w > maxWidth )
      maxWidth = w;
    height += listBox1.GetItemHeight( i );
  }
}
// 16 is scrollbar width
listBox1.Width = (int) ( maxWidth + 6 +
  ( ( height > listBox1.Height - 4 ) ? 16 : 0 ) );

Contributed from George Shepherd's Windows Forms FAQ