ComboBox In C#

C# ComboBox Control

The ComboBox control provides combined functionality of a text box and a listbox in a single control. Only one list item is displayed at one time in a ComboBox and rest of the available items are loaded in a drop down list.

Creating a ComboBox

We can create a ComboBox control using a Forms designer at design-time or using the ComboBox class in C# code at run-time.

To create a ComboBox control at design-time, you simply drag and drop a ComboBox control from Toolbox to a Form in Visual Studio. After you drag and drop a ComboBox on a Form, the ComboBox looks like Figure 1.  

ComboBox In C#

Figure 1

Once a ComboBox is on the Form, you can move it around and resize it and set its properties and events using the Properties and Events windows.

Creating a ComboBox control at run-time includes creating an instance of ComboBox class, set its properties and add ComboBox instance to the Form controls.

First step to create a dynamic ComboBox is to create an instance of ComboBox class.

The following code snippet creates a ComboBox control object.

ComboBox comboBox1 = new ComboBox(); 

In the next step, you set properties of a ComboBox control.

The following code snippet sets location, width, height, background color, foreground color, Text, Name, and Font properties of a ComboBox.

comboBox1.Location = new System.Drawing.Point(20, 60);
comboBox1.Name = "comboBox1";
comboBox1.Size = new System.Drawing.Size(245, 25);
comboBox1.BackColor = System.Drawing.Color.Orange;  
comboBox1.ForeColor = System.Drawing.Color.Black; 

Once the ComboBox control is ready with its properties, the next step is to add the ComboBox to a Form.

To do so, we use Form.Controls.Add method.

The following code snippet adds a ComboBox control to the current Form.

Controls.Add(comboBox1); 

Setting ComboBox Properties

Alternatively, you can set control properites at design time. The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 2.

ComboBox In C#

Figure 2

Name

Name property represents a unique name of a ComboBox control. It is used to access control in the code. The following code snippet sets and gets the name and text of a ComboBox control.

comboBox1.Name = "comboBox1";  

Location, Height, Width and Size

The Location property is a type of Point that specifies the starting position of the ComboBox on a Form. You may also use Left and Top properties to specify the location of a control from the left top corner of the Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a ComboBox control.

comboBox1.Location = New System.Drawing.Point(12, 12);  
comboBox1.Size = New System.Drawing.Size(300, 25);  
comboBox1.Width = 300;  
comboBox1.Height = 25;

DropDownHeight and DropDownWidth

You can control the size of the dropdown area of a ComboBox. The DropDownHeight and DropDownWidth properties represent the height and width of the dropdown area in pixel respectively. If the DropDownWidth and DropDownHeight properties are less than the Width and Height values, they will not be applicable. If all the items do not fit in the size of the dropdown area, the scrollbars will appear as you can see from Figure 3.

ComboBox In C#

Figure 3

The following code snippet sets the height and width of the dropdown area of a ComboBox.

comboBox1.DropDownHeight = 50;  
comboBox1.DropDownWidth = 300;  

Font

Font property represents font of text of a ComboBox control. If you click on the Font property in Properties window, you will see Font name, size and other font options.

comboBox1.Font = new Font("Georgia", 16);  

Background and Foreground

BackColor and ForeColor properties are used to set background color and foreground color of a ComboBox respectively. If you click on these properties in Properties window, the Color Dialog pops up.

Alternatively, you can set background color and foreground color at run-time. The following code snippet sets BackColor and ForeColor properties.

comboBox1.BackColor = System.Drawing.Color.Orange;  
comboBox1.ForeColor = System.Drawing.Color.Black;  

The new ComboBox with background and foreground looks like Figure 4.

ComboBox In C#

Figure 4

ComboBox Items

The Items property is used to add and access items in a ComboBox. We can add items to a ComboBox at design-time from Properties Window by clicking on Items Collection as you can see in Figure 5.

ComboBox In C#

Figure 5

When you click on the Collections, the String Collection Editor window will pop up where you can type strings. Each line added to this collection will become a ComboBox item. I add four items as you can see from Figure 6.

ComboBox In C#

Figure 6

The ComboBox looks like Figure 7.

ComboBox In C#

Figure 7

Alternatively, you can add same items at run-time by using the following code snippet. 

comboBox1.Items.Add("Mahesh Chand");  
comboBox1.Items.Add("Mike Gold");  
comboBox1.Items.Add("Praveen Kumar");  
comboBox1.Items.Add("Raj Beniwal"); 

Getting All Items

To get all items of a control, we use Items property that is a collection of items.

The following code snippet loops through all items and adds item contents to a StringBuilder and displays in a MessageBox.

private void GetItemsButton_Click(object sender, EventArgs e)  
{  
    StringBuilder sb = new StringBuilder();  
    foreach (string name in Combo1.Items)  
    {  
        sb.Append(name);  
        sb.Append(" ");  
    }  
    MessageBox.Show(sb.ToString());  
}

Selected Text and Item

Text property is used to set and get text of a ComboBox. The following code snippet sets and gets current text of a ComboBox.

comboBox1.Text = "Mahesh Chand";  
MessageBox.Show(comboBox1.Text);

We can also get text associated with currently selected item by using Items property.

string selectedItem = comboBox1.Items[comboBox1.SelectedIndex].ToString();

Why the value of ComboBox.SelectedText is Empty?

SelectedText property gets and sets the selected text in a ComboBox only when a ComboBox has focus on it. If the focus moves away from a ComboBox, the value of SelectedText will be an empty string. To get current text in a ComboBox when it does not have focus, use Text property.

DataSource

A ComboBox can be used to bind to a collection of items. DataSource property is used to get and set a data source to a ComboBox. The data source can be a collection or object that implements IList interface such as an array, a collection, or a DataSet.

The following code snippet binds an enumeration converted to an array to a ComboBox.

comboBox1.DataSource = System.Enum.GetValues(typeof(ComboBoxStyle));  

DropDownStyle

DropDownStyle property is used to gets and sets the style of a ComboBox. It is a type of ComboBoxStyle enumeration.

The ComboBoxStyle enumeration has following three values.

  • Simple - List is always visible and the text portion is editable.
  • DropDown – List is displayed by clicking the down arrow and that the text portion is editable.
  • DropDownList - List is displayed by clicking the down arrow and that the text portion is not editable.

The following code snippet sets the DropDownStyle property of a ComboBox to DropDownList. 

comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;  

DroppedDown

If set true, the dropped down portion of the ComboBox is displayed. By default, this value is false.

Sorting Items

The Sorted property set to true, the ComboBox items are sorted. The following code snippet sorts the ComboBox items. 

comboBox1.Sorted = true; 

Find Items

FindString method is used to find a string or substring in a ComboBox. The following code snippet finds a string in a ComboBox and selects it if found.

private void FindButton_Click(object sender, EventArgs e)  
{  
   int index = comboBox1.FindString(textBox1.Text);  
   if (index < 0)  
   {  
      MessageBox.Show("Item not found.");  
      textBox1.Text = String.Empty;  
   }  
   else  
   {  
      comboBox1.SelectedIndex = index;  
   }  
}

ComboBox SelectedIndexChanged Event Hander

CheckedChanged and CheckStateChanged are two important events for a ComboBox control. The CheckedChanged event occurs when the value of the Checked property changes. The CheckStateChanged event occurs when the value of the CheckState property changes.

To add these event handlers, you go to Events window and double click on CheckedChanged and CheckedStateChanged events as you can see in Figure 8.

ComboBox In C#

Figure 8

The following code snippet defines and implements these events and their respective event handlers.

comboBox1.SelectedIndexChanged += new System.EventHandler(ComboBox1_SelectedIndexChanged);  
private void ComboBox1_SelectedIndexChanged(object sender,System.EventArgs e)  
{  
   MessageBox.Show(comboBox1.Text);  
}

Summary

In this article, we discussed discuss how to create a ComboBox control in Windows Forms at design-time as well as run-time. After that, we discussed how to use its various properties and methods to build real world applications.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.