Listbox Control In C#



Source code: ColorListBox.zip

Overview: In this article we will see how to write owner drawn ListBoxcontrol. Typically, Windows handles the task of drawing the items to display inthe ListBox. You can use the DrawModeproperty and handle the MeasureItemand DrawItemevents to provide the ability to override the automatic drawing that Windowsprovides and draw the items yourself. You can use owner-drawn ListBoxcontrols to display variable-height items, images, or a different color or fontfor the text of each item in the list.

Description: We start by creating a Windows Application. Add ListBoxto the form and set its DrawMode property to OwnerDrawVariable.Alternatively you can add following line to InitializeComponent()function of your form,

//lstColor is ListBox control
 this.lstColor.DrawMode =System.Windows.Forms.DrawMode.OwnerDrawVariable;

Next add following lines below above line

//tell windows we are interested in drawing items inListBox on our own
this.lstColor.DrawItem += newDrawItemEventHandler(this.DrawItemHandler);
//tell windows we are interested in providing item size
this.lstColor.MeasureItem += newSystem.Windows.Forms.MeasureItemEventHandler(this.MeasureItemHandler);

 By doing this, windows will send us DrawItem and MeasureItem event foreach item added to ListBox.

Next, add handlers for these events

private voidDrawItemHandler(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    e.DrawFocusRectangle();
    e.Graphics.DrawString(data[e.Index],newFont(FontFamily.GenericSansSerif, 14, FontStyle.Bold),newSolidBrush(color[e.Index]),e.Bounds);
 

}

private voidMeasureItemHandler(object sender,MeasureItemEventArgs e)
{
    e.ItemHeight= 22;
}

In above code date is array that holds items to be inserted and color isarray of class Color
Thats it. We are done!!!
 

Send me your comments at lparam@hotmail.com

About Author: Sanjay Ahuja is a Bachelor of Engineer and done his CDAC fromPune,India. He is currently working as a consultant for Verizon

Most Commented Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

One Response to “Listbox Control In C#”

  1. i am making a english to hindi dictionary in c# please send me resource code or some help me