Owner Draw ListBox Control in Windows Forms and C#


Overview

In this article we will see how to write owner drawn ListBox control. Typically, Windows handles the task of drawing the items to display in the ListBox. You can use the DrawMode property and handle the MeasureItem and DrawItem events to provide the ability to override the automatic drawing that Windows provides and draw the items yourself. You can use owner-drawn ListBox controls to display variable-height items, images, or a different color or font for the text of each item in the list.

Description

We start by creating a Windows Application. Add ListBox to the form and set its DrawMode property to OwnerDrawVariable. Alternatively you can add following line to InitializeComponent() function of your form,

//lstColor is ListBox control
 this.lstColor.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;

Next add following lines below above line

//tell windows we are interested in drawing items in ListBox on our own
this.lstColor.DrawItem += new DrawItemEventHandler(this.DrawItemHandler);
//tell windows we are interested in providing  item size
this.lstColor.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.MeasureItemHandler);

 By doing this, windows will send us DrawItem and MeasureItem event for each item added to ListBox.

Next, add handlers for these events

private void DrawItemHandler(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.DrawFocusRectangle();
e.Graphics.DrawString(data[e.Index],
new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold),new
SolidBrush(color[e.Index]),e.Bounds);
}

private void MeasureItemHandler(object sender, MeasureItemEventArgs e)
{
e.ItemHeight= 22;
}

In above code date is array that holds items to be inserted and color is array of class Color.

That's it. We are done!!!

Up Next
    Ebook Download
    View all
    Learn
    View all