i want to change the color of a selected items from a list box control how to do that in windows(Winforms)
A:
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.
Neil Barnwell
2009-08-07 09:44:24
Listbox Items are of type System.Object, no background.
Henk Holterman
2009-08-07 13:07:04
Oh. I thought the OP was asking how to change the colour of a control based on the selection in a listbox. I didn't realise he wanted each listbox item itself to have a different colour. Oh well. Easy come, easy go.
Neil Barnwell
2009-08-07 13:56:39
+3
A:
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
JDunkerley
2009-08-07 13:11:19
+1 - This is very similar to our implementation of this as well.
Refracted Paladin
2009-08-07 13:17:20