C# Windows Forms ComboBox Examples

Learn ComboBox comprehensively using several examples.

What is a ComboBox?

It is a Control that Represents a Windows combo box control.

Here is its definition;

[System.ComponentModel.DefaultBindingProperty("Text")]
public class ComboBox : System.Windows.Forms.ListControl

And its inheritance hierarchy:

Object -> MarshalByRefObject -> Component -> Control -> ListControl -> ComboBox

The Windows Forms ComboBox control is used to display data in a drop-down combo box. By default, the ComboBox control appears in two parts: the top part is a text box that allows the user to type a list item. The second part is a list box that displays a list of items from which the user can select one.

A ComboBox displays a text box combined with a ListBox, which enables the user to select items from the list or enter a new value.

The DropDownStyle property specifies whether the list is always displayed or whether the list is displayed in a drop-down. The DropDownStyle property also specifies whether the text portion can be edited. See ComboBoxStyle for the available settings and their effects. There is no setting to always display the list and disallow entering a new value. To display a list to which no new values can be added, use a ListBox control.

To add or remove objects in the list at run time, use methods of the ComboBox.ObjectCollection class (through the Items property of the ComboBox). You can 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. You can delete items with the Remove method or clear the entire list with the Clear method.

In addition to display and selection functionality, the ComboBox also provides features that enable you to efficiently add items to the ComboBox and to find text within the items of the list. With the BeginUpdate and EndUpdate methods, you can add a large number of items to the ComboBox without the control being repainted each time an item is added to the list. The FindString and FindStringExact methods enable you to search for an item in the list that contains a specific search string.

You can use these properties to manage the currently selected item in the list, the Text property to specify the string displayed in the editing field, the SelectedIndex property to get or set the current item, and the SelectedItem property to get or set a reference to the object.

Let us look at some ComboBox examples:

Example 1: ComboBox Example

The following code example is a complete application showing how you can use the Add method to add items to a ComboBox, the FindString method to find items in a ComboBox, and the BeginUpdate and EndUpdate methods to efficiently add a large number items to a ComboBox. The ability to store values that are different from displayed text is inherited from ListControl. For an example of how to use this feature, see the ListControl class.

You must add references to the System.Drawing and System.Windows.Forms namespaces to run this example.

using System;
using System.Windows.Forms;

namespace Win32Form1Namespace {

    public class Win32Form1 : System.Windows.Forms.Form {
        private System.Windows.Forms.Button addButton;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Button addGrandButton;
        private System.Windows.Forms.ComboBox comboBox1;
        private System.Windows.Forms.Button showSelectedButton;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button findButton;
        private System.Windows.Forms.Label label1;

        public Win32Form1() {
            this.InitializeComponent();
        }

        [System.STAThreadAttribute()]
        public static void Main() {
            System.Windows.Forms.Application.Run(new Win32Form1());
        }

        private void InitializeComponent() {
            this.addButton = new System.Windows.Forms.Button();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.addGrandButton = new System.Windows.Forms.Button();
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.showSelectedButton = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.findButton = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.addButton.Location = new System.Drawing.Point(248, 32);
            this.addButton.Size = new System.Drawing.Size(40, 24);
            this.addButton.TabIndex = 1;
            this.addButton.Text = "Add";
            this.addButton.Click += new System.EventHandler(this.addButton_Click);
            this.textBox2.Location = new System.Drawing.Point(8, 64);
            this.textBox2.Size = new System.Drawing.Size(232, 20);
            this.textBox2.TabIndex = 6;
            this.textBox2.Text = "";
            this.addGrandButton.Location = new System.Drawing.Point(8, 96);
            this.addGrandButton.Size = new System.Drawing.Size(280, 23);
            this.addGrandButton.TabIndex = 2;
            this.addGrandButton.Text = "Add 1,000 Items";
            this.addGrandButton.Click += new System.EventHandler(this.addGrandButton_Click);
            this.comboBox1.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
                        | System.Windows.Forms.AnchorStyles.Right);
            this.comboBox1.DropDownWidth = 280;
            this.comboBox1.Items.AddRange(new object[] {"Item 1",
                        "Item 2",
                        "Item 3",
                        "Item 4",
                        "Item 5"});
            this.comboBox1.Location = new System.Drawing.Point(8, 248);
            this.comboBox1.Size = new System.Drawing.Size(280, 21);
            this.comboBox1.TabIndex = 7;
            this.showSelectedButton.Location = new System.Drawing.Point(8, 128);
            this.showSelectedButton.Size = new System.Drawing.Size(280, 24);
            this.showSelectedButton.TabIndex = 4;
            this.showSelectedButton.Text = "What Item is Selected?";
            this.showSelectedButton.Click += new System.EventHandler(this.showSelectedButton_Click);
            this.textBox1.Location = new System.Drawing.Point(8, 32);
            this.textBox1.Size = new System.Drawing.Size(232, 20);
            this.textBox1.TabIndex = 5;
            this.textBox1.Text = "";
            this.findButton.Location = new System.Drawing.Point(248, 64);
            this.findButton.Size = new System.Drawing.Size(40, 24);
            this.findButton.TabIndex = 3;
            this.findButton.Text = "Find";
            this.findButton.Click += new System.EventHandler(this.findButton_Click);
            this.label1.Location = new System.Drawing.Point(8, 224);
            this.label1.Size = new System.Drawing.Size(144, 23);
            this.label1.TabIndex = 0;
            this.label1.Text = "Test ComboBox";
            this.ClientSize = new System.Drawing.Size(292, 273);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {this.comboBox1,
                        this.textBox2,
                        this.textBox1,
                        this.showSelectedButton,
                        this.findButton,
                        this.addGrandButton,
                        this.addButton,
                        this.label1});
            this.Text = "ComboBox Sample";
        }

        private void addButton_Click(object sender, System.EventArgs e) {
           comboBox1.Items.Add(textBox1.Text);
        }

        private void addGrandButton_Click(object sender, System.EventArgs e) {
            comboBox1.BeginUpdate();
            for (int i = 0; i < 1000; i++) {
                comboBox1.Items.Add("Item 1" + i.ToString());
            }
            comboBox1.EndUpdate();
        }

        private void findButton_Click(object sender, System.EventArgs e) {
            int index = comboBox1.FindString(textBox2.Text);
            comboBox1.SelectedIndex = index;
        }

        private void showSelectedButton_Click(object sender, System.EventArgs e) {
            int selectedIndex = comboBox1.SelectedIndex;
            Object selectedItem = comboBox1.SelectedItem;

            MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "n" +
                            "Index: " + selectedIndex.ToString());
        }
    }
}

Example 2: Several ComboBoxes

This example will comprise the following files:

  • ComboBox.cs

Step 1: Create Project

  1. The first step is to create a C# Project.
  2. Go to FILE-->New-->Project to create a new project.

Step 2: Write Code

Write Code as follows:

*(a). ComboBox.cs

Create a file named ComboBox.cs

Here is the full code

using System;
using System.Windows.Forms;

namespace Examples {
  class Form1 : Form {
    // The main entry point for the application.
    public static void Main() {
      Application.EnableVisualStyles();
      Application.Run(new Form1());
    }

    public Form1() {
      comboBox1.Location = new System.Drawing.Point(10, 10);
      comboBox1.Items.AddRange(new string[] { "item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10" });
      comboBox1.SelectedIndex = 0;
      comboBox1.Parent = this;

      comboBox2.Location = new System.Drawing.Point(10, 50);
      comboBox2.DropDownStyle = ComboBoxStyle.DropDownList;
      comboBox2.Items.AddRange(new string[] { "item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10" });
      comboBox2.SelectedIndex = 1;
      comboBox2.Parent = this;

      comboBox3.Location = new System.Drawing.Point(10, 90);
      comboBox3.DropDownStyle = ComboBoxStyle.Simple;
      comboBox3.Items.AddRange(new string[] { "item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10" });
      comboBox3.SelectedIndex = 2;
      comboBox3.Parent = this;

      Text = "ComboBox example";
    }

    private ComboBox comboBox1 = new ComboBox();
    private ComboBox comboBox2 = new ComboBox();
    private ComboBox comboBox3 = new ComboBox();
  };
}

Run

Simply copy the source code into your C# Project,Build and Run. Alternatively download the code using the links provided below, then open the .csproj project, build and run.

Reference

Download the code using the below links:

Number Link
1. Download Example
2. Follow code author

ComboBox.DropDownStyle Property

Gets or sets a value specifying the style of the combo box.

public System.Windows.Forms.ComboBoxStyle DropDownStyle { get; set; }

The DropDownStyle property specifies whether the list is always displayed or whether the list is displayed in a drop-down. The DropDownStyle property also specifies whether the text portion can be edited. See ComboBoxStyle for the available settings and their effects. There is no setting to always display the list and disallow entering a new value. To display a list to which no new values can be added, use a ListBox control.

Here is an example:

DropDownStyle Example

The following code example demonstrates setting the DropDownStyle property. To run the example, paste the following code in a form. Call the InitializeComboBox method in the form's constructor or Load event.

internal System.Windows.Forms.ComboBox ComboBox1;
  private string[] animals;

This method initializes the owner-drawn combo box. The drop-down width is set much wider than the size of the combo box to accomodate the large items in the list. The drop-down style is set to ComboBox.DropDown, which requires the user to click on the arrow to see the list.

  private void InitializeComboBox()
  {
      this.ComboBox1 = new ComboBox();
      this.ComboBox1.DrawMode = 
          System.Windows.Forms.DrawMode.OwnerDrawVariable;
      this.ComboBox1.Location = new System.Drawing.Point(10, 20);
      this.ComboBox1.Name = "ComboBox1";
      this.ComboBox1.Size = new System.Drawing.Size(100, 120);
      this.ComboBox1.DropDownWidth = 250;
      this.ComboBox1.TabIndex = 0;
      this.ComboBox1.DropDownStyle = ComboBoxStyle.DropDown;
      animals = new string[]{"Elephant", "c r o c o d i l e", "lion"};
      ComboBox1.DataSource = animals;
      this.Controls.Add(this.ComboBox1);

Hook up the MeasureItem and DrawItem events:

      this.ComboBox1.DrawItem += 
          new DrawItemEventHandler(ComboBox1_DrawItem);
      this.ComboBox1.MeasureItem += 
          new MeasureItemEventHandler(ComboBox1_MeasureItem);
  }

If you set the Draw property to DrawMode.OwnerDrawVariable, you must handle the MeasureItem event. This event handler will set the height and width of each item before it is drawn.

  private void ComboBox1_MeasureItem(object sender, 
      System.Windows.Forms.MeasureItemEventArgs e)
  {

      switch(e.Index)
      {
          case 0:
              e.ItemHeight = 45;
              break;
          case 1:
              e.ItemHeight = 20;
              break;
          case 2:
              e.ItemHeight = 35;
              break;
      }
      e.ItemWidth = 260;
  }

You must handle the DrawItem event for owner-drawn combo boxes. This event handler changes the color, size and font of an item based on its position in the array.

  private void ComboBox1_DrawItem(object sender, 
      System.Windows.Forms.DrawItemEventArgs e)
  {

      float size = 0;
      System.Drawing.Font myFont;
      FontFamily family = null;

      System.Drawing.Color animalColor = new System.Drawing.Color();
      switch(e.Index)
      {
          case 0:
              size = 30;
              animalColor = System.Drawing.Color.Gray;
              family = FontFamily.GenericSansSerif;
              break;
          case 1:
              size = 10;
              animalColor = System.Drawing.Color.LawnGreen;
              family = FontFamily.GenericMonospace;
              break;
          case 2:
              size = 15;
              animalColor = System.Drawing.Color.Tan;
              family = FontFamily.GenericSansSerif;
              break;
      }

Draw the background of the item:

      e.DrawBackground();

Create a square filled with the animals color. Vary the size of the rectangle based on the length of the animals name.

      Rectangle rectangle = new Rectangle(2, e.Bounds.Top+2, 
              e.Bounds.Height, e.Bounds.Height-4);
      e.Graphics.FillRectangle(new SolidBrush(animalColor), rectangle);

Draw each string in the array, using a different size, color, and font for each item:

      myFont = new Font(family, size, FontStyle.Bold);
      e.Graphics.DrawString(animals[e.Index], myFont, 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();
  }

Here is the full code:

internal System.Windows.Forms.ComboBox ComboBox1;
  private string[] animals;

  private void InitializeComboBox()
  {
      this.ComboBox1 = new ComboBox();
      this.ComboBox1.DrawMode = 
          System.Windows.Forms.DrawMode.OwnerDrawVariable;
      this.ComboBox1.Location = new System.Drawing.Point(10, 20);
      this.ComboBox1.Name = "ComboBox1";
      this.ComboBox1.Size = new System.Drawing.Size(100, 120);
      this.ComboBox1.DropDownWidth = 250;
      this.ComboBox1.TabIndex = 0;
      this.ComboBox1.DropDownStyle = ComboBoxStyle.DropDown;
      animals = new string[]{"Elephant", "c r o c o d i l e", "lion"};
      ComboBox1.DataSource = animals;
      this.Controls.Add(this.ComboBox1);

      this.ComboBox1.DrawItem += 
          new DrawItemEventHandler(ComboBox1_DrawItem);
      this.ComboBox1.MeasureItem += 
          new MeasureItemEventHandler(ComboBox1_MeasureItem);
  }

  private void ComboBox1_MeasureItem(object sender, 
      System.Windows.Forms.MeasureItemEventArgs e)
  {

      switch(e.Index)
      {
          case 0:
              e.ItemHeight = 45;
              break;
          case 1:
              e.ItemHeight = 20;
              break;
          case 2:
              e.ItemHeight = 35;
              break;
      }
      e.ItemWidth = 260;
  }

  private void ComboBox1_DrawItem(object sender, 
      System.Windows.Forms.DrawItemEventArgs e)
  {

      float size = 0;
      System.Drawing.Font myFont;
      FontFamily family = null;

      System.Drawing.Color animalColor = new System.Drawing.Color();
      switch(e.Index)
      {
          case 0:
              size = 30;
              animalColor = System.Drawing.Color.Gray;
              family = FontFamily.GenericSansSerif;
              break;
          case 1:
              size = 10;
              animalColor = System.Drawing.Color.LawnGreen;
              family = FontFamily.GenericMonospace;
              break;
          case 2:
              size = 15;
              animalColor = System.Drawing.Color.Tan;
              family = FontFamily.GenericSansSerif;
              break;
      }

      e.DrawBackground();

      Rectangle rectangle = new Rectangle(2, e.Bounds.Top+2, 
              e.Bounds.Height, e.Bounds.Height-4);
      e.Graphics.FillRectangle(new SolidBrush(animalColor), rectangle);

      myFont = new Font(family, size, FontStyle.Bold);
      e.Graphics.DrawString(animals[e.Index], myFont, System.Drawing.Brushes.Black, new RectangleF(e.Bounds.X+rectangle.Width, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));

      e.DrawFocusRectangle();
  }

ComboBoxStyle Enum

This property Specifies the ComboBox style.

public enum ComboBoxStyle

Here is its inheritance hierarchy:

Object -> ValueType -> Enum -> ComboBoxStyle

Here are its fields:

(a). DropDown 1

This Specifies that the list is displayed by clicking the down arrow and that the text portion is editable. This means that the user can enter a new value and is not limited to selecting an existing value in the list. When using this setting, the Append value of AutoCompleteMode works the same as the SuggestAppend value. This is the default style.

(b). DropDownList 2

Specifies that the list is displayed by clicking the down arrow and that the text portion is not editable. This means that the user cannot enter a new value. Only values already in the list can be selected. The list displays only if AutoCompleteMode is Suggest or SuggestAppend.

(c). Simple 0

Specifies that the list is always visible and that the text portion is editable. This means that the user can enter a new value and is not limited to selecting an existing value in the list.

ComboBoxStyle Enum Example

The following code example demonstrates how to initialize a ComboBox control by setting the ComboBox.DropDownStyle property to a ComboBoxStyle value.

The DropDownStyle property specifies whether the list is always displayed or whether the list is displayed in a drop-down. The DropDownStyle property also specifies whether the text portion can be edited.

// Declare comboBox1 as a ComboBox.
internal System.Windows.Forms.ComboBox ComboBox1;

// This method initializes the combo box, adding a large string array
// but limiting the drop-down size to six rows so the combo box doesn't 
// cover other controls when it expands.
private void InitializeComboBox()
{
    this.ComboBox1 = new System.Windows.Forms.ComboBox();
    string[] employees = new string[]{"Hamilton, David", "Hensien, Kari",
            "Hammond, Maria", "Harris, Keith", "Henshaw, Jeff D.", 
            "Hanson, Mark", "Harnpadoungsataya, Sariya", 
            "Harrington, Mark", "Harris, Keith", "Hartwig, Doris", 
            "Harui, Roger", "Hassall, Mark", "Hasselberg, Jonas", 
            "Harnpadoungsataya, Sariya", "Henshaw, Jeff D.", 
            "Henshaw, Jeff D.", "Hensien, Kari", "Harris, Keith", 
            "Henshaw, Jeff D.", "Hensien, Kari", "Hasselberg, Jonas",
            "Harrington, Mark", "Hedlund, Magnus", "Hay, Jeff", 
            "Heidepriem, Brandon D."};

    ComboBox1.Items.AddRange(employees);
    this.ComboBox1.Location = new System.Drawing.Point(136, 32);
    this.ComboBox1.IntegralHeight = false;
    this.ComboBox1.MaxDropDownItems = 5;
    this.ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
    this.ComboBox1.Name = "ComboBox1";
    this.ComboBox1.Size = new System.Drawing.Size(136, 81);
    this.ComboBox1.TabIndex = 0;
    this.Controls.Add(this.ComboBox1);

    // Associate the event-handling method with the 
    // SelectedIndexChanged event.
    this.ComboBox1.SelectedIndexChanged += 
        new System.EventHandler(ComboBox1_SelectedIndexChanged);
}

ComboBox.SelectedItem Property

Gets or sets currently selected item in the ComboBox.

[System.ComponentModel.Bindable(true)]
[System.ComponentModel.Browsable(false)]
public object SelectedItem { get; set; }

Example

The following code example shows the usage of the SelectedIndex and the SelectedItem properties. The example is part of a complete code example in the ComboBox class overview.

When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index. If the object does not exist in the list, the SelectedIndex property is left at its current value.

private void showSelectedButton_Click(object sender, System.EventArgs e) {
    int selectedIndex = comboBox1.SelectedIndex;
    Object selectedItem = comboBox1.SelectedItem;

    MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "n" +
                    "Index: " + selectedIndex.ToString());
}

The ComboBox class searches for the specified object by using the IndexOf method. This method uses the Equals method to determine equality.

ComboBox.SelectedIndex Property

Gets or sets the index specifying the currently selected item.

[System.ComponentModel.Browsable(false)]
public override int SelectedIndex { get; set; }

Example

The following code example show how to use the FindString method and SelectedIndex property. The example is part of a complete example in the ComboBox class overview.

This property indicates the zero-based index of the currently selected item in the combo box list. Setting a new index raises the SelectedIndexChanged event.

SelectedIndex, SelectedValue, and FormattingEnabled are related as follows:

  1. If FormattingEnabled is false, SelectedIndex will not be set to -1 when SelectedValue is blank.
  2. If FormattingEnabled is true, SelectedIndex will be set to -1 when SelectedValue is blank.
private void findButton_Click(object sender, System.EventArgs e) {
    int index = comboBox1.FindString(textBox2.Text);
    comboBox1.SelectedIndex = index;
}

To deselect the currently selected item, set the SelectedIndex to -1. You cannot set the SelectedIndex of a ComboBox item to -1 if the item is a data-bound item.

ComboBox.ObjectCollection Class

Represents the collection of items in a ComboBox.

[System.ComponentModel.ListBindable(false)]
public class ComboBox.ObjectCollection : System.Collections.Generic.IComparer<System.Windows.Forms.ComboBox.ObjectCollection.Entry>, System.Collections.IList

Here is its inheritance hierarchy:

Object -> ComboBox.ObjectCollection

The System.Windows.Forms.ComboBox.ObjectCollection class encapsulates the items in the ComboBox. The object collection of a combo box can be used to manage many types of objects, including strings, images, and custom business objects.

You can add items to the collection in several ways. The Add method adds one object to the collection. To add a number of objects to the collection, it is best to create an array of items and assign with the AddRange method. To insert an object at a specific location within the collection, you can use the Insert method. To remove items at a known index in the collection you can use either the Remove method or the RemoveAt method. The Clear method removes all the items from the collection.

In addition to methods and properties for adding and removing items, the System.Windows.Forms.ComboBox.ObjectCollection also provides methods to find items within the collection. The Contains method enables you to determine if an object is a member of the collection. Once you know that the item is located within the collection, you can use the IndexOf method to determine where the item is located within the collection.