Ankur
Ankur

Reputation: 350

How to change text color of an item in a ListBox

I have a ListBox with several items, also I have a connect button. On the connect button _Click event i am connecting each item to the server.

I want to change the text color of the item to green after the Connect button has been clicked. And red for those for whom Connect button have not been clicked and Vice Versa.

Upvotes: 4

Views: 10922

Answers (1)

dotNET
dotNET

Reputation: 35450

Use owner-draw mode of the ListBox. That will solve your problem. Select your ListBox in design-mode and change DrawMode property to OwnerDrawFixed. Now attach a handler to DrawItem event and then use Graphics class's methods to draw your string in any color or font you like. An example of what you need to do in DrawItem would be:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), listBox1.Font, Brushes.Green, e.Bounds);
}

Upvotes: 4

Related Questions