The Items property is used to add and work with
items in a ComboBox. We can add items to a ComboBox at design-time from
Properties Window by clicking on Items Collection as you can see in Figure 5.
When you click on the Collections, the String
Collection Editor window will pop up where you can type strings. Each line added
to this collection will become a ComboBox item. I add four items as you can see
from Figure 6.
The ComboBox looks like Figure 7.
You can add same items at run-time by using the
following code snippet.
Getting All Items
To get all items, we use the Items property and
loop through it to read all the items. The following code snippet loops through
all items and adds item contents to a StringBuilder and displays in a MessageBox.
sb As New
For Each item
Selected Text and Item
Text property is used to set and get text of a
ComboBox. The following code snippet sets and gets current text of a ComboBox.
We can also get text associated with currently
selected item by using Items property.
String = ComboBox1.Items(ComboBox1.SelectedIndex)
Why the value of ComboBox.SelectedText is Empty?
SelectedText property gets and sets the selected text in a ComboBox only when a
ComboBox has focus on it. If the focus moves away from a ComboBox, the value of
SelectedText will be an empty string. To get current text in a ComboBox when it
does not have focus, use Text property.
DataSource property is used to get and set a data source to a ComboBox. The data
source can be a collection or object that implements IList interface such as an
array, a collection, or a DataSet. The following code snippet binds an
enumeration converted to an array to a ComboBox.
ComboBox1.DataSource = System.Enum.GetValues(GetType(ComboBoxStyle))
DropDownStyle property is used to gets and sets the style of a ComboBox. It is a
type of ComboBoxStyle enumeration.
ComboBoxStyle enumeration has following three values.
- List is always visible and the text portion is editable.
â€" List is displayed by clicking the down arrow and that the text portion is
- List is displayed by clicking the down arrow and that the text portion is not
following code snippet sets the DropDownStyle property of a ComboBox to
set true, the dropped down portion of the ComboBox is displayed. By default,
this value is false.
The Sorted property set to true, the ComboBox
items are sorted. The following code snippet sorts the ComboBox items.
The FindString method is used to find a string
or substring in a ComboBox. The following code snippet finds a string in a
ComboBox and selects it if found.
sender As System.Object,
ByVal e As System.EventArgs)
Dim index As
Integer = ComboBox1.FindString(TextBox1.Text)
If (index < 0) Then
ComboBox1.SelectedIndex = index