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.
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();
}
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 IS with a ListView, with something like:
// Set the background of the first item in the list
MyListView.Items[0].BackColor = Color.Red;
I tried to follow the answer posted here, and the Background was really set in the color I wanted. But the text of the items did not appear. Seems like we have to call the DrawString() additionally.
I tried to follow the answer posted here, and the Background was really set in the color I wanted. But the text of the items did not appear. We have to call the DrawString() additionally.
Thanks for the answer (by Grad van Horck), it guided me in the correct direction.
To support text (not just background color) here is my fully working code:
private void lbReports_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);
int index = e.Index;
if (index >= 0 && index < lbReports.Items.Count)
{
string text = lbReports.Items[index].ToString();
Graphics g = e.Graphics;
Color color = (selected) ? Color.FromKnownColor(KnownColor.Highlight) : (((index % 2) == 0) ? Color.White : Color.Gray);
g.FillRectangle(new SolidBrush(color), e.Bounds);
// Print text
g.DrawString(text, e.Font, (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush,
lbReports.GetItemRectangle(index).Location);
}
e.DrawFocusRectangle();
}
The above adds to the given code and will show the proper text plus highlight selected item.