CodeItBetter Programming Another VB Programming Blog

How to use ADO to load data into a FlexGrid control

Posted on January 4, 2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'Database - How to use ADO to load data into a FlexGrid control
'Open the database and execute the query. Loop through the recordset's Fields
'array to get the field names and use them as column headers.

'For each record in the Recordset, loop through the fields saving their values
'in the FlexGrid.

'Keep track of the largest text width in each column and make each column big
'enough to display the text.

Private Sub Form_Load()
    Dim db_file As String
    Dim statement As String
    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim c As Integer
    Dim r As Integer
    Dim col_wid() As Single
    Dim field_wid As Single
 
    ' Get the data.
    db_file = App.Path
    If Right$(db_file, 1) <> "\" Then db_file = db_file & "\"
    db_file = db_file & "books.mdb"
 
    ' Open a connection.
    Set conn = New ADODB.Connection
    conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & db_file & ";" & _
        "Persist Security Info=False"
    conn.Open
 
    ' Select the data.
    statement = "SELECT * FROM Books ORDER BY Title"
 
    ' Get the records.
    Set rs = conn.Execute(statement, , adCmdText)
 
    ' Use one fixed row and no fixed columns.
    MSFlexGrid1.Rows = 2
    MSFlexGrid1.FixedRows = 1
    MSFlexGrid1.FixedCols = 0
 
    ' Display column headers.
    MSFlexGrid1.Rows = 1
    MSFlexGrid1.Cols = rs.Fields.Count
    ReDim col_wid(0 To rs.Fields.Count - 1)
    For c = 0 To rs.Fields.Count - 1
        MSFlexGrid1.TextMatrix(0, c) = rs.Fields(c).Name
        col_wid(c) = TextWidth(rs.Fields(c).Name)
    Next c
 
    ' Display the values for each row.
    r = 1
    Do While Not rs.EOF
        MSFlexGrid1.Rows = MSFlexGrid1.Rows + 1
        For c = 0 To rs.Fields.Count - 1
            MSFlexGrid1.TextMatrix(r, c) = rs.Fields(c).Value
 
            ' See how big the value is.
            field_wid = TextWidth(rs.Fields(c).Value)
            If col_wid(c) < field_wid Then col_wid(c) = field_wid
        Next c
 
        rs.MoveNext
        r = r + 1
    Loop
 
    ' Close the recordset and connection.
    rs.Close
    conn.Close
 
    ' Set the column widths.
    For c = 0 To MSFlexGrid1.Cols - 1
        MSFlexGrid1.ColWidth(c) = col_wid(c) + 240
    Next c
End Sub
Filed under: Database Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.