sharparena.com

  • Increase font size
  • Default font size
  • Decrease font size

C# ListBox with Variable Height Items

E-mail Print PDF
User Rating: / 0
PoorBest 

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:

Normal listbox

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:
Owner-draw list box


Owner-draw list box

And that was fast and easy!

Last Updated on Tuesday, 21 April 2009 08:13  

Related articles

Polls

What is your .NET language of choice?
 

Who's Online?

We have 1 guest online

Did you know

Did you know you can submit articles for publishing using the submission form if you are authenticated on the site?