Windows Forms 2.0 –ComboBox Control Recipes

Posted by: Suprotim Agarwal , on 6/15/2008, in Category WinForms & WinRT
Views: 36744
Abstract: In this article, we will explore how to perform some common tasks using the ComboBox Control of Windows Forms 2.0.
Windows Forms 2.0 – ComboBox Control Recipes
A ComboBox is a text box combined with a ListBox. The ComboBox allows users to insert text in an editing field (TextBox)  or to make a selection from a defined set of possibilities.
How Do I Get Started With The ComboBox Control
A ComboBox is a text box combined with a ListBox. The ComboBox allows users to insert text in an editing field (TextBox)  or to make a selection from a defined set of possibilities.
The DropDownStyle property in the Appearance section of the properties window determines the style of the ComboBox. The default value is set to DropDown which means the text portion is editable and thus you can type any value in the editable area of the ComboBox. If you set the DropDownStyle property to DropDownList, The user cannot directly edit the text portion. You can select only valid values from the list. Setting it to simple makes The text portion editable. The list portion is always visible.
To add objects to the list at run time, assign an array of object references with the AddRange method. The list then displays the default string value for each object. You can add individual objects with the Add method.
The following code example shows how you can create a ComboBox programmatically by setting a few properties. It uses the AddRange method to add items to a ComboBox. The code also adds an event handler which is currently left for the users to implement.
// ComboBox cmb;
// System.Object[] ItemRange;
private void CreateComboBox()
cmb = new ComboBox();
cmb.Location = new Point(12,30);
cmb.Size = new Size(168,20);
cmb.DropDownWidth = 150;
cmb.SelectedIndexChanged += new EventHandler(cmb_SelectedIndexChanged);
private void AddItems()
ItemRange = new System.Object[5];
for (int i = 0; i <= 4; i++)
ItemRange[i] = "Item " + i;
// Currently an empty implementation of the IndexChanged Event handler
private void cmb_SelectedIndexChanged(object sender, System.EventArgs e)
      // Add Your Code here
How Do I Add/Remove Items From A ComboBox
The ComboBox.Items property enables you to obtain a reference to the list of items that are currently stored in the ComboBox. With this reference, you can add items, remove items, and obtain a count of the items in the collection
Items can be added to a Windows Forms combo box, list box, or checked list box in a variety of ways, because these controls can be bound to a variety of data sources. The items displayed are usually strings; however, any object can be used.
I have already demonstrated how to add a range of items in the previous section 4.1 using AddItems() method. Let me demonstrate how to add/remove individual items.
The following example requires two buttons (btnAddItems and btnRemoveItems) to be placed on the form.
// Add individual items
private void btnAddItems_Click(object sender, EventArgs e)
// To insert at last position
int cnt = cmb.Items.Count;
if (txtItems.Text != String.Empty)
cmb.Items.Insert(cnt, "Item " + cnt);
txtItems.Text = ""; // Emtpy text box after addition
// To remove individual items
private void btnRemoveItems_Click(object sender, EventArgs e)
// To remove item at a specified index, use RemoveAt
// cmb.Items.RemoveAt(0);
Note : To Remove all items in the combobox, use cmb.Items.Clear()
How Do I Search An Item In the ComboBox Control
The ComboBox.FindStringExact Method finds the first item in the combo box that matches the specified string. The return value is the zero-based index of the first item found. In case of no match is found, it returns -1. The parameter passed to this method is a string which is compared against the text associated with the items in the combo box list. The search looks for a match starting from the beginning of the text, returning the first item in the list that matches the specified substring. There also exists a FindStringExact(String, Int32) method which takes a string as well as an integer as parameters. This method is used to find the first item after the specified index that matches the specified string.
Note : The search performed by this method is not case-sensitive.
The following code example demonstrates how to use the FindStringExact methods to search the ComboBox. To run the example, enter the text to be searched in a TextBox named txtItems and call the FindStringInCombo() method in the form's btnSearchComboBox_Click Event.
private void btnSearchComboBox_Click(object sender, EventArgs e)
private void FindStringInCombo()
int res = -1;
if (txtItems.Text != String.Empty)
// FindStringExact method Finds the first
// occurrence in the list.
res = cmb.FindStringExact(txtItems.Text);
      // FindStringExact returns -1 if string not found
if (res != -1)
MessageBox.Show(String.Format("The string {0} was found at position {1}", txtItems.Text, res));
cmb.SelectedIndex = res;
MessageBox.Show("The string you supplied is not present in the list");
MessageBox.Show("Enter a String to Search","Search String not supplied");
How Do I Create An AutoComplete ComboBox
The Visual Studio .NET 2005 brings autocomplete to the mainstream WinForms development. This capability was added manually in previous versions of .NET, but is now built in. In .NET 2.0 there is a new property on the ComboBox that sets an option that controls how automatic completion works for the ComboBox. The values available for this property are Append, Suggest, SuggestAppend, and None. The default is None.
The following example demonstrates how to add the autocomplete feature to a ComboBox. To implement this, set ComboBox.DropDownStyle to DropDown and ComboBox.AutoCompleteMode to either Append/Suggest/SuggestAppend.
If you require the drop down list to show up automatically when the user starts typing, then you can cause the Combobox to drop down by setting its DroppedDown property = true.
In the CreateComboBox(), add these following lines of code:
// Add these lines to enable AutoComplete
cmb.DropDownStyle = ComboBoxStyle.DropDown;
cmb.AutoCompleteMode = AutoCompleteMode.Append;
cmb.KeyPress += new KeyPressEventHandler(cmb_KeyPress);
Add an event handler to cause the ComboBox to dropdown once the user starts typing.
private void cmb_KeyPress(object sender, KeyPressEventArgs e)
//To enable the comboBox to drop.
cmb.DroppedDown = true;
How Do I OwnerDraw A ComboBox
The ComboBox.DrawMode property sets a value that is used to specify if a control is drawn by the operating system or if your own code handles the drawing of the control. These DrawMode enumeration values are:
Normal - All the elements in a control are drawn by the operating system and are of the same size. 
OwnerDrawFixed - All the elements in the control are drawn manually and are of the same size. 
OwnerDrawVariable - All the elements in the control are drawn manually and can differ in size. 
To perform the drawing of each item into the ComboBox, you use the DrawItem event. You can use this event to specify the tasks needed to draw items in the ComboBox.
The following example demonstrates how to create owner-drawn ComboBox items. The code uses the DrawMode property to specify that the items drawn are OwnerDrawFixed. The DrawItem event performs the drawing of each item into the ComboBox.
In the CreateComboBox() method, add these two lines of code :
// Owner Draw
cmb.DrawMode = DrawMode.OwnerDrawFixed;
cmb.DrawItem += new DrawItemEventHandler(cmb_DrawItem);
// Custom Owner Draw
private void cmb_DrawItem(object sender, DrawItemEventArgs e)
System.Drawing.Font fFont;
FontFamily fFamily = null;
FontStyle style = FontStyle.Bold;
float fontsize = 0;
System.Drawing.Color clr = new System.Drawing.Color();
switch (e.Index)
case 0:
fontsize = 8;
clr = Color.Gray;
fFamily = FontFamily.GenericSansSerif;
style = FontStyle.Bold;
case 1:
fontsize = 9;
clr = Color.Gray;
fFamily = FontFamily.GenericMonospace;
style = FontStyle.Italic;
case 2:
fontsize = 10;
clr = Color.Tan;
fFamily = FontFamily.GenericSansSerif;
style = FontStyle.Regular;
case 3:
fontsize = 11;
clr = Color.DarkRed;
fFamily = FontFamily.GenericSerif;
style = FontStyle.Regular;
case 4:
fontsize = 12;
clr = Color.Fuchsia;
fFamily = FontFamily.GenericMonospace;
style = FontStyle.Strikeout;
// Draw the background of the item.
// Displays a rectangle of different colors
Rectangle rectangle = new Rectangle(4, e.Bounds.Top + 3,
e.Bounds.Height, e.Bounds.Height - 8);
e.Graphics.FillRectangle(new SolidBrush(clr), rectangle);
// Draws the specified text string in the specified rectangle
// using a different size, color, and font for each item.
fFont = new Font(fFamily, fontsize, style);
e.Graphics.DrawString((String)ItemRange[e.Index], fFont, System.Drawing.Brushes.Black, new RectangleF(e.Bounds.X + rectangle.Width, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));
// Draw the focus rectangle if the mouse hovers over an item.
Conclusion :
In this article, we saw a recipe approach to performing some of the most common tasks with the ComboBox Control. I hope this article was useful and I thank you for viewing it.
 If you liked the article,  Subscribe to my RSS Feed.  
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Avinash on Thursday, June 26, 2008 6:17 AM
Suprotim May i know how to add item text and Value to the combobox of windows forms? as searched for it dint got any thing :(
Comment posted by Suprotim Agarwal on Friday, June 27, 2008 7:06 AM
Avinash: Try this code

public class Customer
public string Name {get;}
public int ID {get;}

comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Name" ;

Populate it using:
Customer cust = new Customer();
cust.ID = 1 ;
cust.Name = "Cust1";

and so on...I hope you get the idea.
Comment posted by jignesh patel on Wednesday, August 27, 2008 3:06 AM
this code is greate.

but i want my combobox style is DropDownList
on that this code is not work.
please help me.
Comment posted by Suprotim Agarwal on Wednesday, August 27, 2008 11:55 AM
Jignesh: Mention the part of the code tht does not work. If you set the DropDownStyle property to DropDownList, the user cannot directly edit the text portion.
Comment posted by Roger Messar on Tuesday, February 24, 2009 9:51 AM
So many articles assume too much knowledge of technologies like JavaScript or even HTML. I'm a Visual Studio developer, and this is the first time I found information that I could use without feeling like a dummy. Thanks for the excellent article!
Comment posted by Suprotim Agarwal on Thursday, February 26, 2009 6:30 AM
Roger: Thanks for the kind words :)
Comment posted by V.R.J.Daniel Vinos on Thursday, September 3, 2009 8:16 AM
Thanks a lot. I am new to win forms and I was searching for this for a very long time.
Good job.
Comment posted by ramz buenz on Tuesday, October 27, 2009 3:34 AM
what i like is that. a combo box in then i have code taken from a table. for example i want to list all countries with codes on it.
Comment posted by fastwindowstweaker on Saturday, January 28, 2012 1:46 AM
what a article!But anyway thanks for sharing





Free DNC .NET Magazine



jQuery CookBook