Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

20. Windows Forms ListBox

20.5 How can 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.

     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);
     }
     g.Dispose();

     listBox1.Width = (int) (maxWidth + 6 + ((height > listBox1.Height - 4) ? 16 : 0)); // 16 is scrollbar width