Using different colors in List Boxes

T

tantiboh

I'd like to affect specific items in a List Box. In other words, I'd like to take any one (or more) elements of the List Box Collection and, say, turn it red, or turn it bold.

Anybody know how to do this?

**********************************************************************
Sent via Fuzzy Software @ http://www.fuzzysoftware.com/
Comprehensive, categorised, searchable collection of links to ASP & ASP.NET resources...
 
B

Bjorn Abelli

...
I'd like to affect specific items in a List Box.
In other words, I'd like to take any one (or more)
elements of the List Box Collection and, say, turn
it red, or turn it bold.

Anybody know how to do this?

An example:

Set the DrawMode property of the ListBox to DrawMode.OwnerDrawFixed.

this.listBox1.DrawMode =
System.Windows.Forms.DrawMode.OwnerDrawFixed;

Set the DrawItem event of the ListBox to respond to a method, e.g.:

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



Create the method, e.g:


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

// Draw the background of the ListBox control for each item.
e.DrawBackground();

// Create a new Brush and initialize to a Black colored brush by default.
Brush myBrush = Brushes.Green;

// 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.Red;
break;
case 1:
myBrush = Brushes.Orange;
break;
case 2:
myBrush = Brushes.Purple;
break;
}

// Draw the current item text based on the current Font
// and the custom brush settings.
e.Graphics.DrawString( listBox1.Items[e.Index].ToString(),
e.Font, myBrush, e.Bounds,
StringFormat.GenericDefault);

// If the ListBox has focus, draw a focus rectangle around the selected
item.
e.DrawFocusRectangle();
}


// Bjorn A
 
T

tantiboh

Excellent! Thanks

**********************************************************************
Sent via Fuzzy Software @ http://www.fuzzysoftware.com/
Comprehensive, categorised, searchable collection of links to ASP & ASP.NET resources...
 

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