1
votes

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

2

2 Answers

8
votes

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

0
votes

Assuming you're working with WinForms:

Most controls will have a BackColor and BorderColor property. You could add the Color objects to your listbox (the color name should be displayed as Color.ToString() returns the name), then use listbox.SelectedItems[0] to get the color and update the other controls' BackColor etc.