Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Owner drawn ListBox

2.71/5 (5 votes)
31 Oct 2008CPOL1 min read 1   344  
A listbox which supports custom drawing properties for each list item.

Introduction

This is a list box which supports drawing list box items with custom fore colors. This could easily be modified to support more features, but I kept it simple and will allow others to explore.

The list box draw mode has been changed to:

VB
ListBox.DrawMode = Windows.Forms.DrawMode.OwnerDrawFixed

This property change tells the list box to raise the DrawItem event. The DrawItem will be responsible for drawing all the list items. In this case, the list box will attempt to cast each list item to the ICustomListBoxItemSupport interface; if that works, it will then pull the TextColor and display the value using the interface. This allows each list item to provide its own color when drawing the text. If the cast does not work, the list box should still work close to the existing list box functionality.

The benefits to using the ICustomListBoxItemSupport interface is you can implement the interface in existing objects which inherit from others, which makes it easier to add to existing business objects.

Background

I needed a way to indicate some list items as different (or errors, in my case).

Using the code

Have your list items implement the ICustomListBoxItemSupport interface, and the custom list box will do the rest.

VB
Imports System.Drawing

''' <summary>
''' Example custom list box item.
''' </summary>
''' <remarks></remarks>
Public Class Person

    Implements ICustomListBoxItemSupport

    Private m_Name As String = String.Empty

    Public Property Name() As String
        Get
            Return m_Name
        End Get
        Set(ByVal value As String)
            m_Name = value
        End Set
    End Property


#Region "ICustomListBoxItemSupport implements"
     Public ReadOnly Property TextColor() As System.Drawing.Color _
           Implements ICustomListBoxItemSupport.TextColor
        Get
            If m_Name.Length > 25 Then
                Return Color.DarkRed
            Else
                Return SystemColors.WindowText
            End If
        End Get
    End Property

    Public Property DisplayValue() As String _
           Implements ICustomListBoxItemSupport.DisplayValue
        Get
            Return Me.Name
        End Get
        Set(ByVal value As String)

        End Set
    End Property

#End Region

End Class

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)