By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,723 Members | 1,223 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,723 IT Pros & Developers. It's quick & easy.

DrawItem event of ListBox and CheckedListBox control

P: n/a
I can not make the DrawItem event to work on the CheckedListBox control. I
suggestion will be highly appreciated.

I have the following code. The code works for ListBox and the second item
(Two) is displayed in red in the ListBox but the CheckedLIstBox displays
everything in black (where it should be displayed as red).

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call
CheckedListBox1.DrawMode = DrawMode.OwnerDrawFixed
AddHandler CheckedListBox1.DrawItem, AddressOf
Me.CheckedListBox1_DrawItem

ListBox1.DrawMode = DrawMode.OwnerDrawFixed
AddHandler ListBox1.DrawItem, AddressOf Me.ListBox1_DrawItem
End Sub

Sub CheckedListBox1_DrawItem(ByVal sender As Object, ByVal e As
System.Windows.Forms.DrawItemEventArgs)
e.DrawBackground()
Dim textBrush As Brush = SystemBrushes.ControlText
Dim drawFont As Font = e.Font
If (CheckedListBox1.Items.Item(e.Index).ToString() = "Two") Then
textBrush = Brushes.Red
drawFont = New Font(drawFont.FontFamily, drawFont.Size,
FontStyle.Bold)
ElseIf (e.State And DrawItemState.Selected) > 0 Then
textBrush = SystemBrushes.HighlightText
End If

e.Graphics.DrawString(CheckedListBox1.Items.Item(e .Index).ToString(),
drawFont, textBrush, e.Bounds.X, e.Bounds.Y)
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
CheckedListBox1.Items.Add("One")
CheckedListBox1.Items.Add("Two")
CheckedListBox1.Items.Add("Three")
CheckedListBox1.Items.Add("Four")
ListBox1.Items.Add("One")
ListBox1.Items.Add("Two")
ListBox1.Items.Add("Three")
ListBox1.Items.Add("Four")
End Sub

Sub ListBox1_DrawItem(ByVal sender As Object, ByVal e As
System.Windows.Forms.DrawItemEventArgs)
e.DrawBackground()
Dim textBrush As Brush = SystemBrushes.ControlText
Dim drawFont As Font = e.Font
If (ListBox1.Items.Item(e.Index).ToString() = "Two") Then
textBrush = Brushes.Red
drawFont = New Font(drawFont.FontFamily, drawFont.Size,
FontStyle.Bold)
ElseIf (e.State And DrawItemState.Selected) > 0 Then
textBrush = SystemBrushes.HighlightText
End If
e.Graphics.DrawString(ListBox1.Items.Item(e.Index) .ToString(),
drawFont, textBrush, e.Bounds.X, e.Bounds.Y)
End Sub
Jul 21 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.