View Single Post
  #2 (permalink)  
Old November 4th, 2004, 05:21 AM
jaucourt jaucourt is offline
Friend of Wrox
Join Date: Jul 2003
Location: York, , United Kingdom.
Posts: 142
Thanks: 0
Thanked 2 Times in 2 Posts

Your best bet, I think, is to change the DrawMode of the listbox to OwnerDrawFixed. From there, you create your method for filling the listbox with items:

Private Sub FillListBox()
    ListBox1.ItemHeight = 24

    ' avoid flickering

    ' fill the list box with ListBox1.Items.Add(item)...
    For each item in collection

    ' Finish the update

End Sub
From there, you need to trap the listbox DrawItem event and draw
each item yourself...
Private Sub OnDrawItem(sender As Object, e as DrawItemEventArgs) Handles ListBox1.DrawItem

    ' need to have an Imports System.Drawing statement for this to work
    Dim rect as Rectangle = e.Bounds

    ' get the object we're dealing with...
    Dim myObj As Object = ListBox1.Items(e.Index)

    If (e.State And DrawItemState.Selected) Then
        ' fill rectangle with highlight colou...r
        e.Graphics.FillRectangle(SystemBrushes.Highlight, rect)
        ' not selected, just fill normally...
        e.Graphics.FillRectangle(SystemBrushes.Window, rect)
    End If

    ' get the colour of the item to be drawn...
    If myObj.Active Then colourName = "Red" Else colourName = "Green"
    ' build a brush of that colour
    Dim myBrush as New SolidBrush(Color.FromName(colourName))

    ' sort out our font - i.e. if it's an active item, make it bold...
    Dim myFont as Font

    If myObj.Active = True Then 
        myFont = New Font(e.Font, FontStyle.Bold)
        myFont = e.Font
    End If

    ' draw the text in the correct colour; this also assumes that the property you want to show is called 'name'...
    e.Graphics.DrawString(myObj.Name, myFont, myBrush, rect.X + 4, rect.Y + 2)

    ' dispose of objects...

End Sub
[Acknowledgement to Francesco Balena's book 'Programming Microsoft Visual Basic .Net' for bits of this answer!]