Using ComboBox In Windows Forms

INTRODUCTION

In this article, I am going to explain how to use a ComboBox in a Windows Forms app using Visual Studio 2017. 

STEP 1 - Create a new project 

Let's create a new project using Visual Studio 2017.

Select New Project->Visual C#->Windows Forms App (.NET Framework), give your project a name and click OK. 

Using ComboBox In Windows Forms 

This action creates a WinForms project with a default form and you should see the Windows designer.

STEP 2 - Drag and Drop Control

Let's add a ComboBox control to the form by dragging it from Toolbox and dropping it to the form. You will see a ComboBox 1 is added to the form. This control is now available to you in the code behind. 

ComboBox Control 

C# controls are located in the Toolbox of the development environment. You can use them to create objects on a form with a simple series of mouse clicks and dragging motions. A ComboBox displays a Textbox combined with Listbox, which enables the user to select items from the list or enter a new value.

DropDown Style

The DropDown Style property enables the ComboBox list to appear in dropdown format. The DropDown Style property also specifies whether the text portion can be edited or not.

Using ComboBox In Windows Forms

Now, let's add another control to the form by dragging another control from Toolbox. You may also want to change the properties of the other control.

Using ComboBox In Windows Forms

Using ComboBox In Windows Forms 

Change the text of button controls to what you like.

Using ComboBox In Windows Forms

STEP 3 - Coding for Button Click Event 

You can add a button click event handler by simply double clicking on the button control event handler, we can display the text and index of the text in the Message box .
  1. private void button1_Click(object sender, EventArgs e) {  
  2.     comboBox1.Items.Add("d");  
  3.     string[] items = {  
  4.         "e",  
  5.         "f",  
  6.         "g"  
  7.     };  
  8.     comboBox1.Items.AddRange(items);  
  9. }  
  10. private void button2_Click(object sender, EventArgs e) {  
  11.     MessageBox.Show(comboBox1.SelectedIndex.ToString());  
  12. }  
  13. private void button3_Click(object sender, EventArgs e) {  
  14.     MessageBox.Show(comboBox1.SelectedItem.ToString());  
  15. }  
STEP 4 - Compile and Run

Now simply compile and run the application.

Once you click on the Add by Code button, the output is obtained as given below in the screenshot. 

Using ComboBox In Windows Forms 

Once you click on the View item Index, the output is obtained as given below in the screenshot.

Using ComboBox In Windows Forms 

Once you click on the View item Text button, the output is obtained as given below in the screenshot.

Using ComboBox In Windows Forms 

Summary

In this basic article, you saw how to use a ComboBox control. Hope you found this article interesting. For any feedback, please post it as a comment at the bottom of this article. Thank you!.