Owner Draw ListBox Control in Windows Forms and C#

In this article we will see how to write owner drawn ListBox control. Typically, Windows handles the task of drawing the items to display in the ListBox. You can use the DrawMode property and handle the MeasureItem and DrawItem events to provide the ability to override the automatic drawing that Windows provides and draw the items yourself. You can use owner-drawn ListBox controls to display variable-height items, images, or a different color or font for the text of each item in the list.
We start by creating a Windows Application. Add ListBox to the form and set its DrawMode property to OwnerDrawVariable. Alternatively you can add following line to InitializeComponent() function of your form,
  1. //lstColor is ListBox control  
  2. this.lstColor.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;  
Next add following lines below above line
  1. //tell windows we are interested in drawing items in ListBox on our own  
  2. this.lstColor.DrawItem += new DrawItemEventHandler(this.DrawItemHandler);  
  3. //tell windows we are interested in providing item size   
  4. this.lstColor.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.MeasureItemHandler);  
By doing this, windows will send us DrawItem and MeasureItem event for each item added to ListBox.
Next, add handlers for these events
  1. private void DrawItemHandler(object sender, DrawItemEventArgs e)  
  2. {  
  3.     e.DrawBackground();  
  4.     e.DrawFocusRectangle();  
  5.     e.Graphics.DrawString(data[e.Index],new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold),new SolidBrush(color[e.Index]),e.Bounds);  
  6. }  
  7. private void MeasureItemHandler(object sender, MeasureItemEventArgs e)  
  8. {  
  9.     e.ItemHeight= 22;  
  10. }  
In above code date is array that holds items to be inserted and color is array of class Color.
That's it. We are done!!!