Reputation: 15345
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
Upvotes: 2
Views: 3878
Reputation: 2802
Add a DropDown event to your combobox with the following code:
private void comboBox_DropDown(object sender, EventArgs e)
{
Graphics g = (sender as ComboBox).CreateGraphics();
float longest = 0;
for (int i = 0; i < (sender as ComboBox).Items.Count; i++)
{
SizeF textLength = g.MeasureString((sender as ComboBox).Items[i].ToString(), (sender as ComboBox).Font);
if (textLength.Width > longest)
longest = textLength.Width;
}
if (longest > 0)
(sender as ComboBox).DropDownWidth = (int)longest;
}
Upvotes: 1
Reputation: 4143
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).
Upvotes: 1
Reputation: 8100
See the Graphics.MeasureString method. http://msdn.microsoft.com/en-us/library/9bt8ty58.aspx
Upvotes: 1
Reputation: 97671
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.
Upvotes: 2