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();
精彩评论