Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleSort the columns in an MSFlexGrid control by using a Data control
KeywordsFlexGrid, sort, grid, Data control
CategoriesControls, Algorithms
 
Thanks to Eric Groen.

When the user clicks on a column, rebuild the Data control's RecordSource property so it fetches the data again in the right order.

 
Private Sub MSFlexGrid1_Click()
Static i        As Integer
Dim SQLQuery    As String
Dim strVar      As String
Dim blnDiff     As Boolean
    
    i = i + 1   'Default 'ORDER BY' clause = 'ASC' (i = 1);
    If i > 1 Then i = 0 'when i > 1 then i = 0 which
        ' corresponds to 'ORDER BY' clause = 'DESC'

    With MSFlexGrid1
        If .Row > 1 Then Exit Sub   'Only header responds
            ' to click-event.

        SQLQuery = strSELECT & strTABLE & strORDERBY & _
            .TextMatrix(0, .Col)
        strVar = .TextMatrix(0, .Col)

        'If current field is unequal to previous field then
        ' retrieve default 'ORDER BY' clause.
        If (strVar <> strCons) Then
            strCons = " ASC"
        End If

        blnDiff = CBool(strVar <> strCons)

        If .Row = 1 Then
            'When unequal then retrieve default 'ORDER BY'
            ' clause...:
            If (i = 0 Or i = 1) And blnDiff Then
                SQLQuery = SQLQuery & strCons
            Else
                '...when equal then retrieve default 'ORDER
                ' BY' clause when you click on
                'another fieldheader:
                If i = 1 Then
                    If Right(strSQL, 4) = "DESC" Then
                        SQLQuery = SQLQuery & " ASC"
                    Else
                        SQLQuery = SQLQuery & " DESC"
                    End If
                Else
                    If Right(strSQL, 4) = " ASC" Then
                        SQLQuery = SQLQuery & " DESC"
                    Else
                        SQLQuery = SQLQuery & " ASC"
                    End If
                End If
            End If
        End If
        
        strCons = .TextMatrix(0, .Col)
        Call ExecuteSQL(SQLQuery)
        Caption = strSQL
    End With
End Sub

Private Sub ExecuteSQL(strQuery As String)
    On Error GoTo Error_ExecuteSQL

    Data1.RecordSource = strQuery
    Data1.Refresh
    strSQL = strQuery

    Exit Sub

Error_ExecuteSQL:
    If Err.Number = 3075 Then
        MsgBox Err.Description, vbCritical, CStr("Error: " _
            & Err.Number)
        Exit Sub
    End If
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated