Working With ADOX and Combo Box Control - Employee Form
(Page 4 of 5 )
So let's discuss the form, Employees Information. When this form is first loaded, the “cboEmployees” combo will be loaded with the employees who works in the department.
At the old days we used to add an item to the Combo Box where we had the String that will be displayed in the Combo Box, and the other is the value in that item, where we used to be bounded to the only data type, Integer.
Things have changed; now we can bound the Combo Box to a collection, and this collection will fill the Combo Box without writing a lot of for loops, creating and destroying objects.
When the user selects an item, there is no need to fetch it from the database since we only have its ID.
So let's do the “FillEmployeesCombo” Sub in more details:
Private Sub FillEmployeesCombo()
Dim oDepartment As Department
Try
oDepartment = New Department()
'Bind the combo box to the to the Employees in the
department
With cboEmployees
.DataSource = oDepartment.Employees
.DisplayMember = "Name"
'Select the first Employee in the combobox if
there is any
If .Items.Count > 0 Then
.SelectedIndex = 0
End If
End With
Catch oException As Exception
'Handle the Exception here
MessageBox.Show(oException.ToString)
End Try
End Sub
1) We first created a Department object, in which we have Employees Collection, which is a collection of all the employees who works in that department.
We need to bind the Combo Box control to the Employees Collection. Easy as 1,2,3.
cboEmployees.DataSource = oDepartment.Employees
2) So far so good, but hey, if we bounded to a collection, and each employee has a “Name” and a “Salary”, what would be displayed in the combo box? Yes, we have to specify the property which the Combo Box will be displaying.
cboEmployees.DisplayMember = "Name"
What we did was specify the property name as string; in other words, we told the Combo Box that the collection of object it is binding to has a property called “Name” and that we want to use it to display each item in the Combo Box.
3) Finally, if there are some employees in the department, then we want to select the first item.
If cboEmployees.Items.Count > 0 Then
cboEmployees.SelectedIndex = 0
End If
Next: More on Combo Box >>
More Database Articles
More By Mohammed Qattan