Suppose you need a ListBox that has to display items with the text spread across multiple lines. With the default implementation that would look like this:

The CR LF characters are displayed as squares and the item has only one line of text. To make the list box items have variable height depending on the number of lines of the text you need an owner draw ListBox.
That requires two this:
- set the DrawMode property to OwnerDrawVariable
- handle the MeasureItem and DrawItem event; the first one is fired when the size of the item (height and width) must be computed, and the second when the item is to be displayed
listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);
listBox1.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.listBox1_MeasureItem);
A simple implementation for these handlers is:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.DrawFocusRectangle();
e.Graphics.DrawString(
(string)listBox1.Items[e.Index],
e.Font,
new SolidBrush(e.ForeColor),
e.Bounds);
}
private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = 13 * GetLinesNumber((string)listBox1.Items[e.Index]);
}
private int GetLinesNumber(string text)
{
int count = 1;
int pos = 0;
while ((pos = text.IndexOf("\r\n", pos)) != -1) { count++; pos += 2; }
return count;
}
With those changes made the items should now look like this:


And that was fast and easy!
| < Prev |
|---|





