color a list box's rows (i.e. the background)

Shows how to color individual rows in a listbox in C#.

Download listboxcolorrows.zip

Synopsis:

listboxcolorrows.cs


listboxcolorrows.cs

Synopsis
using System;
using System.Windows.Forms;
using System.Drawing;

public class listboxcolorrows
{
  private ListBox mLB1 = new ListBox();
  private void InitializeComponent()
  {
    //... etc.
    this.mLB1.DrawItem += new DrawItemEventHandler(this.mLB1_DrawItem);
  }

  private void mLB1_DrawItem(object sender, DrawItemEventArgs e)
  {
    String s = (string) mLB1.Items[e.Index];
    e.DrawBackground();
    SolidBrush brush;
    if (s.Equals("red"))
      brush = new SolidBrush(Color.Red);
    else if (s.Equals("yellow"))
      brush = new SolidBrush(Color.Goldenrod);
    else
      brush = new SolidBrush(e.ForeColor);
    e.Graphics.DrawString(s, e.Font, brush, e.Bounds);
  }

}






Contact me about content on this page using john_web-at-arrizza-dot-com
For Web Master or site problems contact: webadmin-at-arrizza-dot-com
Copyright John Arrizza (c) 2001-2010