ListBox selected item custom background and text color
 Posted on April 30, 2013 by CooLMinE   7 Comments
This snippet will allow you to set a custom color for your ListBox’s selected item background as well as the selected items text color.
First make sure that your ListBox’s DrawMode is set to OwnerDrawFixed. This can either by done in the controls properties window or by calling listBox1.DrawMode = DrawMode.OwnerDrawFixed;
Then we need to handle the ListBox’s DrawItem event which is where we will be doing the changes to the selected items.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | private void listBox1_DrawItem(object sender, DrawItemEventArgs e) {     e.DrawBackground();     bool isItemSelected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);     int itemIndex = e.Index;     if (itemIndex >= 0 && itemIndex < listBox1.Items.Count)     {         Graphics g = e.Graphics;         // Background Color         SolidBrush backgroundColorBrush = new SolidBrush((isItemSelected) ? Color.Red : Color.White);         g.FillRectangle(backgroundColorBrush, e.Bounds);         // Set text color         string itemText = listBox1.Items[itemIndex].ToString();         SolidBrush itemTextColorBrush = (isItemSelected) ? new SolidBrush(Color.White) : new SolidBrush(Color.Black);         g.DrawString(itemText, e.Font, itemTextColorBrush, listBox1.GetItemRectangle(itemIndex).Location);         // Clean up         backgroundColorBrush.Dispose();         itemTextColorBrush.Dispose();     }     e.DrawFocusRectangle(); } | 
Feel free to play with the colors to achieve a look you like.

























When I set DrawMode to OwnerDrawFixed, the listBox items do not show.
Same… Did you find a solution?
My c# is not very good. After conversion to VB the ‘handles’ clause appeared to be missing. I added ‘handles Listbox1.DrawItem’ and it works.
Working !!
great code. this works great for me.
thanks
Thank you very much, perfect code !
Thanks. Thanks. Thanks.