To change the color of an item in a ListBox in C#, you can use the DrawItem
event of the ListBox.
This event is raised when an item in the ListBox is drawn, and allows you to customize the appearance of the item.
Here is an example of how to use the DrawItem
event to change the color of an item in a ListBox:
1 2 3 4 5 6 7 8 | private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); e.DrawFocusRectangle(); e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Red), e.Bounds); } |
This code will change the text color of all items in the ListBox to red. You can adjust the color and other properties of the SolidBrush
to suit your needs.
You can also use the DrawMode
property of the ListBox to specify how the items should be drawn. For example:
1 2 3 | listBox1.DrawMode = DrawMode.OwnerDrawFixed; |
This will set the ListBox to use the DrawItem
event to draw the items, allowing you to customize their appearance.
Here is an example of how to use the DrawItem
event to change the color of an item in a ListBox based on its value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace listbox_color { public partial class Form1 : Form { public Form1() { InitializeComponent(); listBox1.DrawMode = DrawMode.OwnerDrawFixed; listBox1.Items.Add(25); listBox1.Items.Add(75); listBox1.Items.Add(50); listBox1.Items.Add(100); listBox1.Items.Add(85); listBox1.Items.Add(30); listBox1.Items.Add(20); } private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); e.DrawFocusRectangle(); int value = (int)listBox1.Items[e.Index]; if (value < 50) { e.Graphics.DrawString(value.ToString(), e.Font, new SolidBrush(Color.Green), e.Bounds); } else if (value >= 50 && value < 75) { e.Graphics.DrawString(value.ToString(), e.Font, new SolidBrush(Color.Yellow), e.Bounds); } else { e.Graphics.DrawString(value.ToString(), e.Font, new SolidBrush(Color.Red), e.Bounds); } } } } |
Output: