Menggunakan ListView sebagai pengganti DataGrid

Loading Data From Database
The ListView control can't be automatically bound to a database through Data, RemoteData, or an ADO Data control. In other words, if you want to load database data into this control you're on your own. The task of filling a ListView control with data read from a recordset isn't conceptually difficult, but you have to account for a few details. First you must retrieve the list of fields contained in the recordset and create a corresponding number of ColumnHeader objects of a suitable width. You also have to discard fields that can't be displayed in ListView controls (for example, BLOB fields), and you must determine the best alignment for each field (to the right for numbers and dates, to the left for all others). A routine that does all this, which you can easily reuse in your applications, is shown below.
Sub LoadListViewFromRecordset(LV As ListView, rs As ADODB.Recordset, _
    Optional MaxRecords As Long)
    Dim fld As ADODB.Field, alignment As Integer
    Dim recCount As Long, i As Long, fldName As String
    Dim li As ListItem
   
    ' Clear the contents of the ListView control.
    LV.ListItems.Clear
    LV.ColumnHeaders.Clear
    ' Create the ColumnHeader collection.
    For Each fld In rs.Fields
        ' Filter out undesired field types.
        Select Case fld.Type
            Case adBoolean, adCurrency, adDate, adDecimal, adDouble
                alignment = lvwColumnRight
            Case adInteger, adNumeric, adSingle, adSmallInt, adVarNumeric
                alignment = lvwColumnRight
            Case adBSTR, adChar, adVarChar, adVariant
                alignment = lvwColumnLeft
            Case Else
                alignment = -1      ' This means "Unsupported field type".
        End Select
        ' If field type is OK, create a column with the correct alignment.
        If alignment <> -1 Then
            ' The first column must be left-aligned.
            If LV.ColumnHeaders.Count = 0 Then alignment = lvwColumnLeft
            LV.ColumnHeaders.Add , , fld.Name, fld.DefinedSize * 200, _
                alignment
        End If
    Next
    ' Exit if there are no fields that can be shown.
    If LV.ColumnHeaders.Count = 0 Then Exit Sub

    ' Add all the records in the recordset.
    rs.MoveFirst
    Do Until rs.EOF
        recCount = recCount + 1
        ' Add the main ListItem object.
        fldName = LV.ColumnHeaders(1).Text
        Set li = LV.ListItems.Add(, , rs.Fields(fldName) & "")
        ' Add all subsequent ListSubItem objects.
        For i = 2 To LV.ColumnHeaders.Count
            fldName = LV.ColumnHeaders(i)
            li.ListSubItems.Add , , rs.Fields(fldName) & ""
        Next
        If recCount = MaxRecords Then Exit Do
        rs.MoveNext
    Loop
End Sub

The LoadListViewFromRecordset routine expects an ADO Recordset and an optional MaxRecords argument that lets you limit the number of records displayed. This is necessary, because—as opposed to what happens with bound controls, which load only the information that is actually displayed—this routine reads all the rows in the recordset, which might be a lengthy process. I suggest that you set MaxRecords to 100 or 200, depending on the type of connection you have to your database and the speed of your CPU.
Another problem you face when loading data from a database is that you might need to manually adjust the width of each column. The LoadListViewFromRecordset routine initializes the width of all ColumnHeader objects using the fields' maximum width, but in most cases values stored in database fields are considerably shorter than this value. Instead of leaving the burden of the manual resizing on your users, you can change all columns' width programmatically using the following routine:
Sub ListViewAdjustColumnWidth(LV As ListView, _
    Optional AccountForHeaders As Boolean)
    Dim row As Long, col As Long
    Dim width As Single, maxWidth As Single
    Dim saveFont As StdFont, saveScaleMode As Integer, cellText As String
    ' Exit if there aren't any items.
    If LV.ListItems.Count = 0 Then Exit Sub
   
    ' Save the font used by the parent form, and enforce ListView's
    ' font. (We need this in order to use the form's TextWidth
    ' method.)
    Set saveFont = LV.Parent.Font
    Set LV.Parent.Font = LV.Font
    ' Enforce ScaleMode = vbTwips for the parent.
    saveScaleMode = LV.Parent.ScaleMode
    LV.Parent.ScaleMode = vbTwips
   
    For col = 1 To LV.ColumnHeaders.Count
        maxWidth = 0
        If AccountForHeaders Then
            maxWidth = LV.Parent.TextWidth(LV.ColumnHeaders(col).Text)+200
        End If
        For row = 1 To LV.ListItems.Count
            ' Retrieve the text string from ListItems or ListSubItems.
            If col = 1 Then
                cellText = LV.ListItems(row).Text
            Else
                cellText = LV.ListItems(row).ListSubItems(col - 1).Text
            End If
            ' Calculate its width, and account for margins.
            ' Note: doesn't account for multiple-line text fields.
            width = LV.Parent.TextWidth(cellText) + 200
            ' Update maxWidth if we've found a larger string.
            If width > maxWidth Then maxWidth = width
        Next
        ' Change the column's width.
        LV.ColumnHeaders(col).width = maxWidth
    Next
    ' Restore parent form's properties.
    Set LV.Parent.Font = saveFont
    LV.Parent.ScaleMode = saveScaleMode
End Sub
To determine the optimal width of all the values stored in a given column, the ListViewAdjustColumnWidth routine evaluates the maximum width of all the strings stored in that column. The problem is that the ListView control doesn't support the TextWidth method, so the routine relies on the TextWidth method exposed by the control's parent form. If a True value is passed in the second argument, the routine also accounts for the Text property of all ColumnHeader objects, so no header title is truncated.
The ListView control already allows you to automatically resize columns to fit their contents, even though this capability hasn't been exposed in the Visual Basic ActiveX control. In fact, you can interactively resize a column to fit the longest item it contains by double-clicking on its right border in the column header (as you would in the Details view mode of Windows Explorer). In the demonstration program on the companion CD, you'll find another version of the ListViewAdjustColumnWidth routine that does the resizing by using API calls instead of plain Visual Basic code. The following code sample shows how to use the ListViewAdjustColumnWidth routine to display all the records in the Orders table of the NorthWind.Mdb database:
Private Sub Form_Load()
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
' WARNING: you might need to modify the DB path in the next line.
cn.Open "Provider=Microsoft.Jet.OLEDB.3.51;" _
& "Data Source=C:\VisStudio\VB98\NWind.mdb"
rs.Open "Orders", cn, adOpenForwardOnly, adLockReadOnly
LoadListViewFromRecordset ListView1, rs
ListViewAdjustColumnWidth ListView1, True
End Sub
Ada dua Procedure yang dibuat Sub LoadListViewFromRecordset (menampilkan data dari database) dan Sub ListViewAdjustColumnWidth (mengatur lebar kolom sesuai panjang field). 
Note : Silahkan mencoba, GAK perlu sibuk ngartiin klo ga ngerti langsung di copy-paste aja dan lihat hasilnya. Jangan lupa databasenya harus dh ada contoh di atas pake database NWind.mdb yang sudah disediakan waktu install VB6.0 dan Tabel yang digunakan "Orders".

0 comments:

Post a Comment

Alexa Rank's

Follow

Powered by Blogger.
Post Comment