Sunday, June 17, 2012

Contoh Mengisi ListView Dengan Database

Option Explicit

Function FillList(strDomain As String, objListView As Object) As Boolean
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim intTotCount As Integer
Dim intCount1 As Integer
Dim intCount2 As Integer
Dim colNew As ColumnHeader
Dim itmNewLine As ListItem

On Error GoTo Err_Handler

objListView.ListItems.Clear
objListView.ColumnHeaders.Clear

Set dbs = CurrentDb
Set rst = dbs.OpenRecordset(strDomain)

For intCount1 = 0 To rst.Fields.Count - 1
Set colNew = objListView.ColumnHeaders.Add(, , rst(intCount1).Name)
Next intCount1

objListView.View = 3

rst.MoveLast
intTotCount = rst.RecordCount
rst.MoveFirst

For intCount1 = 1 To intTotCount
If IsNumeric(rst(0).Value) Then
Set itmNewLine = objListView.ListItems.Add(, , Str(rst(0).Value))
Else
Set itmNewLine = objListView.ListItems.Add(, , rst(0).Value)
End If

For intCount2 = 1 To rst.Fields.Count - 1
itmNewLine.SubItems(intCount2) = rst(intCount2).Value
Next intCount2

rst.MoveNext
Next intCount1

Exit Function

Err_Handler:
If Err = 94 Then
Resume Next
Else
MsgBox "Error: " & Err.Number & vbCrLf & Err.Description
End If
End Function

Private Sub Form_Load()
Dim intResult As Integer
intResult = FillList("Employees", Me!ctlListView)
End Sub