Showing posts with label Visual Basic. Show all posts
Showing posts with label Visual Basic. Show all posts

Monday, December 15, 2008

Counting items in a Combo Box

In Visual Basic, the combo box is a control that can store a list of items. Is it possible to count the number of items that is stored in the combo box? The answer is yes. The keyword to use is the ListCount property. However, in order to count the items according to categories, we have to use the For....Next loop to accomplish the task.

I have written a program to count the number of students who score A, B, C and D respectively. In this program, the user click the "Add Item" button to enter the grades from an Input Box. After entering all the grades, the user can get the statistics by pressing the 'Count" button.

The code is as follows:


Private Sub Command1_Click()
Dim item As String

item = InputBox("Enter an item")

Combo1.AddItem item



End Sub




Private Sub Command2_Click()
Dim count, i As Integer
Dim item1, item2, item3, item4 As Variant

count = Combo1.ListCount

For i = 0 To count

Combo1.Text = Combo1.List(i)

If Combo1.Text = "A" Then
item1 = item1 + 1
ElseIf Combo1.Text = "B" Then
item2 = item2 + 1
ElseIf Combo1.Text = "C" Then
item3 = item3 + 1
ElseIf Combo1.Text = "D" Then
item4 = item4 + 1
End If
Next

Lbl_A.Caption = item1
Lbl_B.Caption = item2
Lbl_C.Caption = item3
Lbl_D.Caption = item4



End Sub

The Output Screen: