Alternate background color of rows in a CheckedListBox?

2.3k Views Asked by At

I need to alternate the color of the items in my CheckedListBox but "alternatingColors" is not a property of CheckedListBox.

How do I go about making the item's colors alternate?

2

There are 2 best solutions below

1
On

The OnDrawItem event is inaccessible by default, but if you derive a new control based on CheckedListBox, then you can override the base event.

public class MyCheckedListBox : CheckedListBox
{
    private SolidBrush primaryColor = new SolidBrush(Color.White);
    private SolidBrush alternateColor = new SolidBrush(Color.LightGreen);

    [Browsable(true)]
    public Color PrimaryColor
    {
        get { return primaryColor.Color; }
        set { primaryColor.Color = value; }
    }

    [Browsable(true)]
    public Color AlternateColor
    {
        get { return alternateColor.Color; }
        set { alternateColor.Color = value; }
    }

    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        base.OnDrawItem(e);

        if (Items.Count <= 0)
            return;

        var contentRect = e.Bounds;
        contentRect.X = 16;
        e.Graphics.FillRectangle(e.Index%2 == 0 ? primaryColor : alternateColor, contentRect);
        e.Graphics.DrawString(Convert.ToString(Items[e.Index]), e.Font, Brushes.Black, contentRect);
    }
}

It'll alternate between white and green by default. Make adjustments in the Properties panel at design time, or during runtime.

enter image description here

1
On

I don't think this is even possible. You may want to consider using a different control for what you need. A DataGridView might be able to work for you better.