Alternative background color for rows in CheckedListBox?

I need to alternate the color of the elements in CheckedListBox

, but "alternatingColors" is not a property CheckedListBox

.

How can I change the color of the elements?

+3


source to share


2 answers


The event is OnDrawItem

not available by default, but if you infer a new based control CheckedListBox

, you can override the underlying 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);
    }
}

      



By default, it will alternate between white and green. Make changes in the Properties panel at design time or at run time.

enter image description here

+2


source


I do not think that's possible. You may want to use a different control for what you need. DataGridView might work better for you.



-2


source







All Articles