Word Wrap in the listbox

M

Matt Brook

Hello,

How do you perform wordwrap in a listbox? I tried an
example with the owner drawn listbox, but the text did
not wrap.

Could someone please help me?

Thanks,
Matt
 
J

Joe White

Try this code:

private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
string itemText = listBox1.Items[e.Index].ToString();
SizeF textSize = e.Graphics.MeasureString(itemText, listBox1.Font,
listBox1.ClientSize.Width);
e.ItemHeight = (int) Math.Round(textSize.Height);
}

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
string itemText = listBox1.Items[e.Index].ToString();
Color bgColor;
Color fgColor;
if ((e.State & DrawItemState.Selected) != 0)
{
bgColor = SystemColors.Highlight;
fgColor = SystemColors.HighlightText;
}
else
{
bgColor = listBox1.BackColor;
fgColor = listBox1.ForeColor;
}
using (Brush bgBrush = new SolidBrush(bgColor))
{
e.Graphics.FillRectangle(bgBrush, e.Bounds);
}
using (Brush fgBrush = new SolidBrush(fgColor))
{
e.Graphics.DrawString(itemText, this.Font, fgBrush, new
RectangleF(e.Bounds.Left, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height));
}
}
 
K

Kevin Westhead

[snip]
e.Graphics.DrawString(outputString, e.Font, b2,
rect.X + 4, rect.Y + 2)

[snip]

StringFormatFlags.NoWrap is implied when passing a Point (x and y are
interpreted as a Point) instead of a Rectangle; try using an overload that
accepts a Rectangle.
 
M

Matt Brook

Kevin,

That worked! Thank you!

Matt
-----Original Message-----

[snip]
e.Graphics.DrawString(outputString, e.Font, b2,
rect.X + 4, rect.Y + 2)

[snip]

StringFormatFlags.NoWrap is implied when passing a Point (x and y are
interpreted as a Point) instead of a Rectangle; try using an overload that
accepts a Rectangle.

--
Kevin Westhead


.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top