C#•Draw ListBox Items

Listing 4. The DrawItem event handles drawing the ListBox items. You create the fancy gradient with round edges for the selected item by using the same GetRoundBox method used to create the ListBox round edges, as well as the GetGradientBrush method used to create the gradient on the form's Label control.

private void listBox1_DrawItem(object sender, 
   System.Windows.Forms.DrawItemEventArgs e)
{
   // Draw the default background of the control
   e.DrawBackground();

   // Cast a variable for the sender
   ListBox l = (ListBox) sender;

   // Create and draw brush for the backcolor
   Brush b = new SolidBrush(l.BackColor);
   e.Graphics.FillRectangle(b, e.Bounds);

   // Dispose of the brush object
   b.Dispose();

   Rectangle rect = e.Bounds;
   rect.Inflate(-2,-2);

   // Draw select background with the fancy
   // gradient, as well as the rounded
   // edges using the GetRoundBox method
   if ((e.State&DrawItemState.Selected) > 0) 
   {
      Brush br = this.GetGradienBrush(rect, 
         Color.Red, Color.White);
      e.Graphics.FillPath(br, 
         this.GetRoundBox(rect,10));
      br.Dispose();
   }

   // Get the size of the selected item,
   // and draw the text of the selected item 
   // into the ListBox
   string text = items[e.Index];
   SizeF sz = e.Graphics.MeasureString(text, 
      l.Font);
   Brush tb = new SolidBrush(color[e.Index]);
   Font fnt = new 
      Font(FontFamily.GenericSansSerif, 
      14, FontStyle.Bold);
   e.Graphics.DrawString(text, fnt, tb, 
      e.Bounds.X +5, 
      e.Bounds.Y+(e.Bounds.Height-sz.Height)/2);
   tb.Dispose();

}