开发者

C# Set ListBox width so that longest item fits

开发者 https://www.devze.com 2023-03-06 18:07 出处:网络
I would like to set my ListBox.Width property so that it is no wider nor narrower than needed, in order to display the items in it. There is a margin of a few pixels between the left of the ListBox an

I would like to set my ListBox.Width property so that it is no wider nor narrower than needed, in order to display the items in it. There is a margin of a few pixels between the left of the ListBox and the start of the text - I wou开发者_开发技巧ld like there to be a similar margin on the right. (i.e. there shouldn't be a large gap, and the letters shouldn't be touching the right edge).

Given that I'm not sure how many pixels a given string will be, I'm not sure how to calculate this width.


I believe you're looking for the MeasureString method of the Graphics class.

Try this:

Graphics graphics = this.createGraphics();
SizeF mySize = graphics.MeasureString("Ahoy there", this.Font);

Hope this helps!


This may be what you want. Also play around with Integral Height and padding.

http://www.codeproject.com/KB/combobox/resizablelistbox.aspx


This worked for me, it wasn't until I changed the width of the listbox that I saw the results I wanted. I looped through the items in the listbox to get the longest. Hope this helps.

int LongestItemLength = 0;
for (int i = 0; i < listBox1.Items.Count;i++ ){
    Graphics g = listBox1.CreateGraphics();
    int tempLength = Convert.ToInt32((
            g.MeasureString(
                    listBox1.Items[i].ToString(), 
                    this.listBox1.Font
                )
            ).Width);
    if (tempLength > LongestItemLength){
        LongestItemLength = tempLength;
    }
}
listBox1.Width = LongestItemLength;
listBox1.Show(); 
0

精彩评论

暂无评论...
验证码 换一张
取 消