winforms Basic controls ComboBox

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

ComboBoxes allow the user to choose one of various options provided by the developer.

We are going to modify the form and add a combobox so the messagebox show us the message that the user want from a list that we will provide.

After adding the combo to the form we now add a list of options to the combo. To do so we need to modify the Items property:

enter image description here

Now we need to modify the code of the click event:

private void cmdShowMessage_Click(object sender, EventArgs e)
{
  string OptionText = cboSelectOption.SelectedItem.ToString();
  MessageBox.Show(OptionText);
}

As you can see we use the SelectedItem property, it contains the object of the selected option. Since we need a string to show and the compiler does not know if the object is or isn't a string, we need to use the ToString() method.

If we run the program we'll be able to choose the option that we prefer and when we click the button the message box will show it:

enter image description here

To be notified when an user selects an item from the combobox, use the SelectionChangeCommitted event. We could use the SelectedIndexChanged event, but this is also raised when we programmatically change the select item in the combobox.



Got any winforms Question?