user1353517
user1353517

Reputation: 300

Change List colour in ListBox

C# I currently have a win form and I can display two lists that I have in a Listbox, however since the two lists are merged the data can be a bit confusing to look at. Is there anyway that I can set List 1's item colour to blue and List 2's item colour to red?

private void updatesum()
{
  listBox.Items.Clear();
  List<String> listOfDels = theDatabase.listDeliveries();
  List<String> listofPicks = theDatabase.listPickups();

  listBox.Items.AddRange(listOfDels.ToArray());
  listBox.Items.AddRange(listofPicks.ToArray());
}

Upvotes: 0

Views: 209

Answers (2)

Tobia Zambon
Tobia Zambon

Reputation: 7629

You have to subscribe the DrawItem of the ListBox and paint yourself the BackColor:

listBox.DrawItem += new DrawItemEventHandler(listBox_DrawItem);

I think your event should be something like this:

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

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

    g.DrawString(listBox.Items[e.Index].ToString(), 
        e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);

    e.DrawFocusRectangle();
}

Upvotes: 2

The_Cthulhu_Kid
The_Cthulhu_Kid

Reputation: 1859

Check out some other answers here and here to similar question SO. I have never done it before but they seem to fit the bill. Hope it helps.

Upvotes: 0

Related Questions