1
Answer

How can I change color on Items in a listBox at runtime?

Sondre Garmo

Sondre Garmo

19y
11.6k
1
I wondering how I can change colors on items in my listbox? I'm using the listBox in a C# windows program and not in a web application. Say that I have 3 items in my listBox. I want to change color on item 2. Then I press a button I want item 2 to change to default color and item 3 to change color. All that will I do in runtime. Can anybody help me please:-) If anybody know, how can I disable items at runtime? I'm using: Microsoft Visual C# .Net 2003 Microsoft .NET Framework 1.1 Sondre
Answers (1)
0
spgilmore

spgilmore

NA 591 0 19y
Use owner-drawing. This example draws every other line in a different color. Create a windows form and add a button and a listbox. In the button click event, put this code: for (int j = 0; j < 10; j++) listBox1.Items.Add("Item " + j.ToString()); Set the listbox DrawMode property to OwnerDrawFixed. This causes the DrawItem event to get fired when an item needs to be rendered. In the DrawItem event, put this code. //Determine characteristics of the current item. int lIndex = e.Index; string lItemText = (string)listBox1.Items[lIndex]; Rectangle lItemBounds = e.Bounds; //We need a Graphics object that we can draw upon using GDI+ functions. Graphics canvas = e.Graphics; //draw the background. Brush lBrush = Brushes.LightSeaGreen; canvas.FillRectangle(lBrush, lItemBounds); //every other line will alternate text color Font lFont = new Font("courier new", 8, FontStyle.Italic); if ((lIndex / 2) * 2 == lIndex) lBrush = Brushes.Purple; else lBrush = Brushes.OliveDrab; //draw the text canvas.DrawString(lItemText, lFont, lBrush, lItemBounds);