Owner drawn ListBox control in VB.NET

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 by self. 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
me.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
addhandler me.lstColor.DrawItem ,addressof me
.DrawItemHandler
'tell windows we are interested in providing item size
addhandler me.lstColor.MeasureItem ,addressof me.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 Sub DrawItemHandler(sender As Object, e As DrawItemEventArgs)e.DrawBackground()
e.DrawFocusRectangle()
e.Graphics.DrawString(data(e.Index), New Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold), New SolidBrush(color(e.Index)), e.Bounds)
End Sub 'DrawItemHandler
Private Sub MeasureItemHandler(sender As Object, e As MeasureItemEventArgs)e.ItemHeight = 22
End Sub 'MeasureItemHandler

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


Similar Articles