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.
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.
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.
Change the text of button controls to what you like.
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 .
- private void button1_Click(object sender, EventArgs e) {
- comboBox1.Items.Add("d");
- string[] items = {
- "e",
- "f",
- "g"
- };
- comboBox1.Items.AddRange(items);
- }
- private void button2_Click(object sender, EventArgs e) {
- MessageBox.Show(comboBox1.SelectedIndex.ToString());
- }
- private void button3_Click(object sender, EventArgs e) {
- MessageBox.Show(comboBox1.SelectedItem.ToString());
- }
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.
Once you click on the View item Index, the output is obtained as given below in the screenshot.
Once you click on the View item Text button, the output is obtained as given below in the screenshot.
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!.