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:
Other People Are Reading
Things you need
- Visual Basic 2008 or later
Add a ComboBox from the components list on the left side of the screen.
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":
ComboBox1.Items.Add("dog") ComboBox1.Items.Add("cat") ComboBox1.Items.Add("mouse") ComboBox1.Items.Add("bird")
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
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."
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 :
This command will remove the "dog" entry from the list.
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:
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:
- The resulting entry will read:
- System.Windows.Forms.ComboBox, Items.Count: 5
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for