Visual basic combo box tutorial

Written by kevin walker

Share

Tweet

Share

Pin

Email

(BananaStock/BananaStock/Getty Images)

The Visual Basic ComboBox component is a common user interface element in Windows programs. It allows the user to select one item from a list of possibilities that are normally hidden, but which drops down when the user clicks on the component. The most important operations for the developer using a ComboBox is adding, removing, clearing and getting the selected item in the ComboBox.

Skill level:

Easy

Other People Are Reading

Things you need

Visual Basic 2008 or later

Show MoreHide

Instructions

1

Add a ComboBox from the components list on the left side of the screen.

2

Add a Button. Go to the Properties window on the bottom left-hand side of the screen and change its text property to read "Populate." Change its name property to "PopulateButton." Double-click the button to create an event function. Paste the following code into the event function named "PopulateButton_Click":

Alternatively, if you don't want to populate the list programmatically, you can populate it using the properties menu. From the Form Designer, click once on the combobox to select it. Find the entry for "Items" in the properties list. It should read "Items" and have a value of "(Collection)." Click the word "Items" and a button will appear with three dots on it. Click that button. A window will pop up asking you to list the items to be added to the list at runtime. To duplicate the effect of the "PopulateButton" created in this step, you would paste the following into this window:

dog cat mouse bird

3

Add another Button. Change its text property to "Delete." Change its name property to "DeleteButton." Double-click this new button to create an event function for when a user clicks it. Paste the following code into the new event function. It's name should be "DeleteButton_Click."

ComboBox1.Items.RemoveAt(ComboBox1.SelectedIndex)

If you can't tell, this will remove the item currently selected from the items listed in the ComboBox.

You can also use the command "ComboBox1.Items.Remove()" to remove an item by its name. For example, the command :

ComboBox2.Items.Remove("dog")

This command will remove the "dog" entry from the list.

4

Add one last button. Name it "ClearButton" and give it the text "Clear." Double-click to create an event for it, and paste the following code there:

ComboBox1.Items.Clear()

This will clear all the items from the ComboBox.

Tips and warnings

Any object can be added to a ComboBox by using its "ToString" method. For example, you can add the ComboBox to itself using the following command: