In this article, we will learn how to use a comboBox control in a Windows Forms application using Visual Studio 2010.
ComboBox control:
ComboBox displays an editable text with a drop-down list of permitted value. ComboBox control represents two part one is textbox and other is listbox.
Properties of ComboBox:
DisplayMember - Indicates the property to display for the items in this control.
Sorted - specifies items in the combobox are sorted.
Text - The text associated with the control.
Items - Items property are used to add an items in the combobox.
AutoCompleteMode - Indicates the text completion behavior of the combobox.
MaxDropDownItems - Indicates maximum number of entries to display in the drop-down list.
ValueMember - Indicates to use as the actual value for the items in the control.
ComboBox Event:
The default event of ComboBox is SelectedIndexChanged which looks like this in code:
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub
ComboBox at Design time:
Figure 1.
Working with ComboBox:
Drag a combobox, button and textbox on the form and add the items on the combobox with the items property and add method.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.Items.Add(".net")
ComboBox1.Items.Add("java")
ComboBox1.Items.Add("oracle")
ComboBox1.Items.Add(2)
End Sub
The form look like this when combobox add items.
Figure 2.
Now double click on the button control and add the following code to select the items from the combobox control to textbox.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex <> -1 Then
TextBox1.Text = ComboBox1.SelectedItem.ToString()
End If
Now select an item from combobox and click on the button it will displays on the textbox.
Figure 3.
Removing items from ComboBox:
You can remove all items or one particular item from the list box part of the ComboxBox.Code to remove a particular item by it's Index number looks like this.
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ComboBox1.Items.RemoveAt(2)
MessageBox.Show(ComboBox1.Items.Count.ToString())
End Sub
Now click on the removeat button the count property display current items number after removing.
Figure 4.
Removing all items from ComboBox:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
ComboBox1.Items.Clear()
End Sub