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);
AddItems();
Controls.Add(cmb);
}
private void AddItems()
{
ItemRange = new System.Object[5];
for (int i = 0; i <= 4; i++)
{
ItemRange[i] = "Item " + i;
}
cmb.Items.AddRange(ItemRange);
}
// 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,txtItems.Text);
}
else
{
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)
{
cmb.Items.Remove(cmb.SelectedItem);
// 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)
{
FindStringInCombo();
}
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;
}
else
{
MessageBox.Show("The string you supplied is not present in the list");
}
}
else
{
MessageBox.Show("Enter a String to Search","Search String not supplied");
txtItems.Focus();
}
}
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;
break;
case 1:
fontsize = 9;
clr = Color.Gray;
fFamily = FontFamily.GenericMonospace;
style = FontStyle.Italic;
break;
case 2:
fontsize = 10;
clr = Color.Tan;
fFamily = FontFamily.GenericSansSerif;
style = FontStyle.Regular;
break;
case 3:
fontsize = 11;
clr = Color.DarkRed;
fFamily = FontFamily.GenericSerif;
style = FontStyle.Regular;
break;
case 4:
fontsize = 12;
clr = Color.Fuchsia;
fFamily = FontFamily.GenericMonospace;
style = FontStyle.Strikeout;
break;
}
// Draw the background of the item.
e.DrawBackground();
// 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.
e.DrawFocusRectangle();
}
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.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
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
The Absolutely Awesome jQuery CookBook.
Suprotim received the prestigious Microsoft MVP award for 17 consecutive years, until he resigned from the program in 2025. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn