How change the color of SelectedItem in CheckedListBox in WindowsForms?

kapil picture kapil · Jan 25, 2010 · Viewed 14.3k times · Source

I want to change the color of the items that are chedked in the CheckedListBox in C# WindowsForms.

Can any one help me to solve this problem!

Answer

Jon Seigel picture Jon Seigel · Nov 6, 2010

This should get you started. I've subclassed a CheckedListBox and overridden the drawing event. The result is all checked items in the list are drawn with a red background.

From playing around with this, if you want the area behind the checkbox to be a different colour as well, use e.Graphics.FillRectangle before calling base.OnDrawItem.

class ColouredCheckedListBox : CheckedListBox
{
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        DrawItemEventArgs e2 =
            new DrawItemEventArgs
            (
                e.Graphics,
                e.Font,
                new Rectangle(e.Bounds.Location, e.Bounds.Size),
                e.Index,
                e.State,
                e.ForeColor,
                this.CheckedIndices.Contains(e.Index) ? Color.Red : SystemColors.Window
            );

        base.OnDrawItem(e2);
    }
}