Live Chat Icon For mobile
Live Chat Icon

How can I set the width of a listbox to fit the text

Platform: WinForms| Category: ListBox

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

Share with

Related FAQs

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

Please submit your question and answer.