Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A C# ColorListBox

0.00/5 (No votes)
29 May 2002 1  
In this article we will see how to write an owner drawn ListBox

Sample Image - ColorListBox.gif

Introduction

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 the 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

Thats it. We are done!

Send me your comments at lparam@hotmail.com

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here