How to draw Listbox items with alternative background colors
Posted on June 24, 2013 by CooLMinE 5 Comments
Some people find it easier to read large amount of data when the rows have an alternative background color instead of always the same. This is called Zebra Striping.
For this example we will look into implementing this technique for our ListBox control so it will look similar to this:
First we need to ensure that the ListBox.DrawMode
property is set to DrawMode.OwnerDrawFixed
. This can be accomplished by either changing the property in the properties window or by placing listBox1.DrawMode = DrawMode.OwnerDrawFixed;
in your form’s constructor or any of the load events.
Then we need to handle the ListBox’s DrawItem
event so we can change the colors as we like.
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) { bool isSelected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected); if (e.Index > -1) { /* If the item is selected set the background color to SystemColors.Highlight or else set the color to either WhiteSmoke or White depending if the item index is even or odd */ Color color = isSelected ? SystemColors.Highlight : e.Index % 2 == 0 ? Color.WhiteSmoke : Color.White; // Background item brush SolidBrush backgroundBrush = new SolidBrush(color); // Text color brush SolidBrush textBrush = new SolidBrush(e.ForeColor); // Draw the background e.Graphics.FillRectangle(backgroundBrush, e.Bounds); // Draw the text e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, textBrush, e.Bounds, StringFormat.GenericDefault); // Clean up backgroundBrush.Dispose(); textBrush.Dispose(); } e.DrawFocusRectangle(); } |
And we are done ! Feel free to modify the example to suit your needs.
Nice Article to solve my problem
One thing I would like to add – My List box stopped showing the elements when I set ListBox.DrawMode property to DrawMode.OwnerDrawFixed. When I reset to DrawMode.OwnerDrawVariable, it started working correctly.Didn’t understand why it happened.
A very helpful article. This is what I was looking for and it offered me a great help and proved to be my savior. Thank you so much.
Instead of
I suggest
This way, DisplayMember doesn’t get broken.
Thanks, didn’t see the GetItemText method, so this saved me a ton of headaches :)