comboBox width depending on longest item

有些话、适合烂在心里 提交于 2020-01-25 04:48:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!