You can iterate through the list to find the longest text extent using MeasureString, adding a fudge factor if the scrollbar 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
Share with