Download VB5 User's Guide
Transcript
In the SmallBusiness class module, add the following declaration. The collection object will be created the first time the Employees variable is referred to in code. Option Explicit Public Employees As New Collection The Form Does All the Work All of the remaining code goes into the form module. Add the following declaration in the Declarations section. Option Explicit Public sbMain As New SmallBusiness The code in the cmdEmployeeAdd_Click event adds a member to the collection. Private Sub cmdEmployeeAdd_Click() Dim empNew As New Employee Static intEmpNum As Integer ’ Using With makes your code faster and more ’ concise (.ID vs. empNew.ID). With empNew ’ Generate a unique ID for the new employee. intEmpNum = intEmpNum + 1 .ID = "E" & Format$(intEmpNum, "00000") .Name = txtName.Text .Salary = CDbl(txtSalary.Text) ’ Add the Employee object reference to the ’ collection, using the ID property as the key. sbMain.Employees.Add empNew, .ID End With txtName.Text = "" txtSalary.Text = "" ’ Click the Refresh List button. cmdListEmployees.Value = True End Sub The code in the cmdListEmployees_Click event procedure uses a For Each ... Next statement to add all the employee information to the Listbox control. Private Sub cmdListEmployees_Click() Dim emp As Employee lstEmployees.Clear For Each emp In sbMain.Employees lstEmployees.AddItem emp.ID & ", " & emp.Name _ & ", " & emp.Salary Next End Sub The cmdEmployeeDelete_Click event uses the Collection object’s Remove method to delete the collection member currently selected in the ListBox control. Private Sub cmdEmployeeDelete_Click() ’ Check to make sure there’s an employee selected. If lstEmployees.ListIndex > -1 Then ’ The first six characters are the ID. sbMain.Employees.Remove _ Left(lstEmployees.Text, 6) End If ’ Click the Refresh List button. cmdListEmployees.Value = True End Sub