Friday, July 3, 2009

Multi Colour Listbox items

We may want to change the color of list box individual items.

For example First Line in Blue Color, Second line in Green, Third line in Black etc

with standard listboxes, all items have same settings, thus you would need to find alternative way.

Here's the Solution:

We have to write own handler for the listbox's DrawItem event.

Steps to do:

Drag and drop a standard ListBox to your .NET WinForm.

Set the ListBox's DrawMode property:

Drag and drop a button

Write the handler for Button Click to populate list box

Write the handler for the DrawItem event:

public Form1()

'Set the drawmode property
listBox1.DrawMode = DrawMode.OwnerDrawFixed;


private void btnPopulateListbox_Click(object sender, EventArgs e)
//Add items


this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);


//Event Handler to change the colour in the list box item

private void listBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)

// Draw the background of the ListBox control for each item.
// Create a new Brush and initialize to a Black colored brush
// by default.

Brush myBrush = Brushes.Black;

// Determine the color of the brush to draw each item based on
// the index of the item to draw.

switch (e.Index)
case 0:
myBrush = Brushes.Blue; //First Row Blue Colour
case 1:
myBrush = Brushes.Green; //Second Row Green Colour
case 2:
myBrush = Brushes.Black; //Third Row Black Colour

// Draw the current item text based on the current
// Font and the custom brush settings.

e.Font, myBrush,e.Bounds,StringFormat.GenericDefault);

// If the ListBox has focus, draw a focus rectangle
// around the selected item.


for more details

No comments:

Post a Comment