tags:

views:

849

answers:

3

i've got a ComboBox that i generate dynamically and fill with some items. i would like to set this control's width to the width of the longest item. how do i count the display width of some text?

edit: i'm using windows forms, but i would like to do it in asp.net as well

+2  A: 

Depends. Are you using ASP.NET or Windows Forms or WPF? Are you using a fixed-width or proportional font?

If you're using Windows Forms, you will want to call MeasureString() in order to find out how wide you want the text to be.

If you're using ASP.NET, you can do something like MeasureString(), but you don't know exactly what font is being rendered on the browser, so you can't just put that in your script.

Dave Markle
i actually hoped that there is some method that does it automatically for combobox - measureString measures the length of the string but of course doesn't take the "arrow down button" of combobox into account so you have to.
agnieszka
In that case, the width of the box can be determined by subtracting the Client Width from the Control's width.
Dave Markle
+1  A: 

See the Graphics.MeasureString method. http://msdn.microsoft.com/en-us/library/9bt8ty58.aspx

petr k.
+1  A: 

If you don't set the width explicitly, browser will render it to be the length of the longest item (if the question is about web forms, of course).

moose-in-the-jungle