Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

20. Windows Forms ListBox

20.4 How do I implement an ownerdrawn listbox?


Check out this sample project at gotnetdot.com. It derives from Form and implements the owner drawing by handling the DrawItem event and MeasureItem event.

You can also download a sample that implements an owner drawn listbox by deriving from ListBox and overriding the virtual methods OnDrawItem and OnMeasureItem. Here is a OnDrawItem override that draws colored rectangles in the listbox.

protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs e)
{
     //undo the selection rect on the old selection
     if( oldSelectedRect != e.Bounds &&
          oldSelectedIndex > -1 && oldSelectedIndex < Items.Count)
     {
          e.Graphics.DrawRectangle(new Pen((Color) Items[oldSelectedIndex], 2), oldSelectedRect);
     }

     //draw the item .. here we just fill a rect
     if( e.Index > -1 && e.Index < Items.Count)
          e.Graphics.FillRectangle(new SolidBrush( (Color)Items[e.Index] ), e.Bounds);
     
     //draw selection rect if needed
     if(SelectedIndex == e.Index)
     {
          e.Graphics.DrawRectangle(new Pen(Color.Black,2), e.Bounds);
          oldSelectedRect = e.Bounds;
          oldSelectedIndex = e.Index;
     }
}