This code colors the item's background based on index - ammend to work on a property of the item at that index.
(Form [
FormMain
] with a
ListBox
added called
listBox
)
using System.Drawing;
using System.Windows.Forms;
namespace CP.QA.WinForms
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
listBox.DrawMode = DrawMode.OwnerDrawFixed;
listBox.DrawItem += new DrawItemEventHandler(listBox_DrawItem);
listBox.Items.AddRange(new object[] { "A", "B", "C" });
}
void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index > -1)
{
if (e.Index == 0)
e.Graphics.FillRectangle(Brushes.Green, e.Bounds);
else if (e.Index == 1)
e.Graphics.FillRectangle(Brushes.Red, e.Bounds);
else
e.DrawBackground();
using (Brush textBrush = new SolidBrush(e.ForeColor))
{
e.Graphics.DrawString(listBox.Items[e.Index].ToString(), e.Font, textBrush, e.Bounds.Location);
}
}
}
}
}