Tech Blog‎ > ‎

VB.NET - Getting Started with Custom Drawing (ListBox)

posted Apr 11, 2013, 7:40 AM by Victor Zakharov   [ updated Apr 11, 2013, 7:42 AM ]
Here I am going to show some basics of custom drawing in VB.NET.
This is not production-class code, but rather a head start for those assessing whether or not it's feasible to custom draw anything (result vs effort).
In this sample project, I will highlight all even items of a ListBox with LightGray color. Here is an extract of how it's done, if you don't want to download anything.

Private Shared Sub ListBox1_DrawItem(sender As System.Object, e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem
  'highlight all even items
  If e.Index Mod 2 = 0 Then
    e.Graphics.FillRectangle(Brushes.LightGray, e.Bounds) 'draw custom background
  Else
    e.DrawBackground() 'draw standard background
  End If
  'draw text
  Dim text As String = CType(sender, ListBox).Items(e.Index).ToString()
  Dim textLocation As New System.Drawing.PointF(e.Bounds.X, e.Bounds.Y)
  e.Graphics.DrawString(text, e.Font, Brushes.Black, textLocation)
  e.DrawFocusRectangle()
End Sub

For this to work, you need to have a ListBox dropped on a form and set its property DrawMode to OwnerDrawFixed or OwnerDrawVariable. I used OwnerDrawFixed for simplicity. The other one allows you to have items of variable height. Several notes on the above code:
  • The handler is declared is Shared, which is not common practice, and just to show that it's not instance dependent. You will probably be using a non-shared handler.
  • DrawItemEventArgs class has a property State of type DrawItemState, which tells whether or not the item is currently Selected, Enabled or other. You may want to differentiate the highlight depending on that in production code. Or add some visual anchors to the item, such as custom icons etc. Keep in mind that not all states are used in all controls, so always refer to documentation when in doubt.
Sample project is attached below.
ċ
ListBoxCustomDraw.zip
(15k)
Victor Zakharov,
Apr 11, 2013, 7:40 AM