问题
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
回答1:
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.
回答2:
See the Graphics.MeasureString method. http://msdn.microsoft.com/en-us/library/9bt8ty58.aspx
回答3:
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).
回答4:
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;
}
来源:https://stackoverflow.com/questions/384596/combobox-width-depending-on-longest-item