Using different colors in List Boxes

  • Thread starter Thread starter tantiboh
  • Start date Start date
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...
 
...
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
 
Excellent! Thanks

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