Background color of a ListBox item (Windows Forms)

Viewed 96351

How can I set the background color of a specific item in a System.Windows.Forms.ListBox?

I would like to be able to set multiple ones if possible.

4 Answers

Probably the only way to accomplish that is to draw the items yourself.

Set the DrawMode to OwnerDrawFixed and code something like this on the DrawItem event:

private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    Graphics g = e.Graphics;

    g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds);

    // Print text

    e.DrawFocusRectangle();
}

The second option would be using a ListView, although they have an other way of implementations (not really data bound, but more flexible in way of columns).

// Set the background to a predefined colour
MyListBox.BackColor = Color.Red;
// OR: Set parts of a color.
MyListBox.BackColor.R = 255;
MyListBox.BackColor.G = 0;
MyListBox.BackColor.B = 0;

If what you mean by setting multiple background colors is setting a different background color for each item, this isn't possible with a ListBox, but it is with a ListView, with something like:

// Set the background of the first item in the list
MyListView.Items[0].BackColor = Color.Red;
Related