0

If i have a listBox , with 10 elements ( or whatever ) , can i select a element and to change it's color ? Only for that element , not for all ...

Something like:

listBox Collection:
ENG
UNG
IT
RO

Like in my example , to choose UNG and to change it's color in green ( or another color )

Edited by charqus: n/a

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by charqus
0

Hi,

I had a similar requirement and found the following solution (can't remember where to give credit). In your case I would replace the switch with one that looks up what colour to display each item from an array or hash-table.

First, set the DrawMode property of your ListBox to OwnerDrawFixed

Second, in your forms Designer.cs file add the following:

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

Finally, add the following to your form:

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

    e.DrawBackground();
    Brush myBrush = Brushes.Black;

    switch (e.Index)
    {
        case 0:
            myBrush = Brushes.Red;
            break;
        case 1:
            myBrush = Brushes.Orange;
            break;
        case 2:
            myBrush = Brushes.Purple;
            break;
    }

    e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), 
        e.Font, myBrush,e.Bounds,StringFormat.GenericDefault);

    e.DrawFocusRectangle();
    }

Hope this helps.

0

Oh yes , thank you very much , it worked !

Edited by charqus: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.