Sunday, January 10, 2010

ComboBox Control in VB 6

ComboBox in VB 6



Combobox is another popular VB control. It has a black downward arrow clicking which a drop down box is displayed with the content of the combo box. User can select a value of their choice.

The items in the combobox is selected using combobox.list(index). Current item can be selected by combobox.list(combobox.listindex), where the listindex property gives the index number of currently selected item.

You can make a combobox, databound using its datasource and datamember properties.

Adding Items:

At Run time: At runtime you can add items in a combobox control using it ComboBox.Add("item name") method.

At Design Time: Use ItemData property of the control to keyin the list of items.

Here is an example of combobox controls that is filled with three colors 'RED', 'GREEN' and 'BLUE'.

To repeat this tutorial create a new standard EXE project in VB 6. Add a Lable control and set its caption property to Colors. Add a ComboBox control and set its name property to cboColors. Add a Command Button and set its name property to cmdFill and caption property to Fill Items. Double click the command button. Add the following source code.

Private Sub cmdFill_Click()
cboColors.AddItem "RED"
cboColors.AddItem "GREEN"
cboColors.AddItem "BLUE"

End Sub

Add another command button and set is name property to cmdShow and caption to Show items. Double click the button. Add the following code.

Private Sub cmdShow_Click()
On Error GoTo Err:
If cboColors.ListIndex = -1 Then
MsgBox "Please select an item"
cboColors.SetFocus
Exit Sub
End If
MsgBox cboColors.List(cboColors.ListIndex)
Exit Sub
Err:
MsgBox Err.Description
End Sub

Run the project by pressing F5 and click Fill Items. Check the ComboBox to see the newly added items.