Step 3: Automatic Sorting

The first step in organizing the data is sorting it. Furthermore, we would like the data to be sorted automatically whenever the user reorders the columns.

After the user reorders the columns, the VSFlexGrid control fires the AfterMoveColumn event. We will add an event handler to sort the data using the Sort property. (Note that if the grid were bound to a database, you would need to set the DataMode property to flexDMFree to be able to sort using the Sort property.)

Here is the code:

    Private Sub fg_AfterMoveColumn(ByVal Col As Long, Position As Long)

        ' sort the data from first to last column

        fg.Select 1, 0, 1, fa.Cols - 1

        fg.Sort = flexSortGenericAscending

        fg.Select 1, 0

    End Sub

The AfterMoveColumn routine starts by selecting the first non-fixed row in the control using the Select method. Next, it sorts the entire control in ascending order using the Sort property.

To start with a sorted grid, we will also add a call to the AfterMoveColumn routine to the end of the Form_Load event handler.

    Private Sub Form_Load()

   

        ' initialize the control

       

        ' define some sample data

       

        ' populate the control with the data

            

        ' organize the data

        fg_AfterMoveColumn 0, 0

   

    End Sub

Press F5 to run the project again, and try reordering the columns by dragging their headings around. Whenever you move a column, the data is automatically sorted, which makes it much easier to interpret. But we're just getting started.