C# – changing selected itms color in a listbox

cwinforms

i want to change the color of a selected items from a list box control how to do that
in windows(Winforms)

Best Answer

As far as I know if you want to do that you need to make the ListBox.DrawMode OwnerDrawFixed and add an event handler on to the DrawItem method.

Something like this might do what you want:

    private void lstDrawItem(object sender, DrawItemEventArgs e)
    {
        ListBox lst = (ListBox)sender;
        e.DrawBackground();
        e.DrawFocusRectangle();

        DrawItemState st = DrawItemState.Selected ^ DrawItemState.Focus;
        Color col = ((e.State & st) == st) ? Color.Yellow : lst.BackColor;

        e.Graphics.DrawRectangle(new Pen(col), e.Bounds);
        e.Graphics.FillRectangle(new SolidBrush(col), e.Bounds);
        if (e.Index >= 0)
        {
            e.Graphics.DrawString(lst.Items[e.Index].ToString(), e.Font, new SolidBrush(lst.ForeColor), e.Bounds, StringFormat.GenericDefault);
        }
    }

Hope it helps James