list item colour

R

Richard Wilde

I am trying to change a colour of a listbox item depending on a value in a
data view
My fields in the dataview are
ID
Name
idCat

ListBox1.ValueMember = "ID"
ListBox1.DataSource = dv1
ListBox1.DisplayMember = "Name"


I have set the listbox drawMode to OwnerdrawFixed and want to be able to
display the name in a different color depending on the idCat. This is where
i have run into problems. I cannot retrieve the idCat from any of the passed
in parameters... Can any one help?



DrawItem event...
dim idCat as int32

idCat = <<HERE>>

Select Case (e.Index)
Case 0
myBrush = Brushes.Red
Case 1
myBrush = Brushes.Orange
Case 2
myBrush = Brushes.Purple
End Select

draw...
 
T

Tim Wilson

Try something like the following.

Private DataTable1 As DataTable

....

DataTable1 = New DataTable("MyTable")
DataTable1.Columns.Add("ID", Type.GetType("System.String"))
DataTable1.Columns.Add("Name", Type.GetType("System.String"))
DataTable1.Columns.Add("Category", Type.GetType("System.Int32"))

Dim rand As New Random
Dim iterator As Integer
For iterator = 0 To 25
DataTable1.Rows.Add(New Object() {Guid.NewGuid().ToString(), "Name" +
iterator.ToString(), rand.Next(0, 4).ToString()})
Next

Me.ListBox1.DisplayMember = "Name"
Me.ListBox1.ValueMember = "ID"
Me.ListBox1.DataSource = DataTable1.DefaultView

....

Private Sub ListBox1_DrawItem(ByVal sender As Object, ByVal e As
System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem
Dim list As ListBox = DirectCast(sender, ListBox)
Dim row As DataRow = DirectCast(list.Items(e.Index), DataRowView).Row
Dim textBrush As Brush

e.DrawBackground()

Select Case (DirectCast(row("Category"), Integer))
Case 0
textBrush = Brushes.Red
Case 1
textBrush = Brushes.Green
Case 2
textBrush = Brushes.Blue
Case 3
textBrush = Brushes.Orange
End Select

e.Graphics.DrawString(DirectCast(row("Name"), String), list.Font,
textBrush, New RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width,
e.Bounds.Height))

e.DrawFocusRectangle()
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top