Word Wrap in the listbox

  • Thread starter Thread starter Matt Brook
  • Start date Start date
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
 
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));
}
}
 
[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,

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


.
 
Back
Top