Here in this source code sample we will discuss how to capture data from you Database Table and displays those data in a combo box.
In this method you can prevent data to be hard coded into your system, we will just have a lookup and displays those lookups in the combo box.
The Code:
First copy this code into your Modules
Option Explicit
Dim conn As ADODB.connection
Dim rs As ADODB.Recordset
-------------------------------------------------
' pupulate element
' @author: Ken
' @date: checkDate 07/28/2009
Public Sub init()
Set conn = New ADODB.connection
Set rs = New ADODB.Recordset
conn.connectionString = connectionString.connectionString
With conn
On Error GoTo errHandler
.Open
End With
Exit Sub
errHandler:
MsgBox Err.Description, vbCritical + vbOKOnly, " Admin: Populate Element Module - Init"
End Sub
Public Sub populateCombo(KeyToCollect As String, dboQuery As String, combo As ComboBox)
Call init
combo.Clear
With rs
'On Error GoTo errHandler
On Error Resume Next
If .State = adStateClosed Then
.Open dboQuery, conn, adOpenKeyset, adLockOptimistic
End If
Do While Not .EOF
combo.AddItem .Fields(KeyToCollect)
.MoveNext
Loop
.Close
End With
conn.Close
Exit Sub
errHandler:
MsgBox Err.Description, vbCritical + vbOKOnly, "Admin: Populate Element MOdule - Populate Combo: Error"
End Sub
'Next is calling the module:
Call PopulateElement.populateCombo("Your Query Here")
Just Experiment on the code and you'll see the best of it.
Good Luck!!!!