I have a Listbox in vb.net. I was able to draw my items (with the DrawItem event) with different colors depending on conditions. It works.
The problem is that the size of the string drawned is wider that the original string as you can see in the following pictures. I use a monospace font, and now the text is not aligned anymore with the textbox above...
Listbox without DrawString
Listbox with Drawstring
My code :
Private Sub ListBoxEvIns_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ListBox_EvIns.DrawItem
ListBox_DrawItem(sender, e, Me.DT_EvIns)
End Sub
Public Sub ListBox_DrawItem(sender As Object, e As DrawItemEventArgs, DT As DataTable)
If DT.Rows.Count() = 0 Then Exit Sub
'Dim F As Font = New Font(e.Font.FontFamily, e.Font.Size * 0.965) 'workaround test
Dim F As Font = New Font(e.Font.FontFamily, e.Font.Size)
e.DrawBackground()
If Dic_ParticipEv_Statut_Brush.Keys.Contains(DT(e.Index).Item("Statut")) Then
e.Graphics.FillRectangle(Dic_ParticipEv_Statut_Brush(DT(e.Index).Item("Statut")), e.Bounds)
Else
e.Graphics.FillRectangle(Brushes.Gray, e.Bounds)
End If
e.Graphics.DrawString(sender.Items(e.Index).ToString(), F, Brushes.White, e.Bounds)
e.DrawFocusRectangle()
End Sub
Can someone explain me what I'm missing ?
First of all, stop creating a font every time you’re painting an item, this wastes precious GDI resources. Use e.Font
directly, without creating another copy.
Ensure you’re using exactly the same font for label and for listbox.
Set UseCompatibleTextRendering
= True
for your label.
I think that’s sufficient.
However, why you’re doing that in the first place? If you’re displaying some multi-column tables, why not use a ListView instead?