ComponentOne FlexGrid for WinForms
Step 3 of 4: Allow Automatic Sorting
FlexGrid for WinForms Tutorials > Data Analysis Tutorial > Step 3 of 4: Allow 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 C1FlexGrid control fires the AfterDragColumn event. We will add an event handler to sort the data in the underlying data table. (If the grid were being used in unbound mode, we would accomplish this using the Sort method.)

Add the following code to the form to sort the record set and rebuild the subtotals when the user drags columns:

To write code in Visual Basic

Visual Basic
Copy Code
Private Sub C1FlexGrid1_AfterDragColumn(ByVal sender As Object, ByVal e As DragRowColEventArgs) Handles C1FlexGrid1.AfterDragColumn
 
    ' Sort the recordset when the user drags columns.
    ' This will cause a data refresh, removing all subtotals and
    ' firing the AfterDataRefresh event, which rebuilds the subtotals.
    Dim sort As String = C1FlexGrid1.Cols(1).Name & ", " & _
                         C1FlexGrid1.Cols(2).Name & ", " & _
                         C1FlexGrid1.Cols(3).Name
    Dim dt As DataTable = C1FlexGrid1.DataSource
    dt.DefaultView.Sort = sort
End Sub

To write code in C#

C#
Copy Code
private void c1FlexGrid1_AfterDragColumn( object sender, DragRowColEventArgs e)
{
    // Sort the recordset when the user drags columns.
    // This will cause a data refresh, removing all subtotals and
    // firing the AfterDataRefresh event, which rebuilds the subtotals.
    string sort = c1FlexGrid1.Cols[1].Name + ", " +
                  c1FlexGrid1.Cols[2].Name + ", " +
                  c1FlexGrid1.Cols[3].Name;
    DataTable dt = (DataTable)c1FlexGrid1.DataSource;
    dt.DefaultView.Sort = sort;
}

Run the program and observe the following:

Run the project and try reordering the first three columns by dragging their headings around. Whenever you move a column, the data is automatically sorted, which makes it easier to interpret.


In the next step, we will add subtotals and an outline tree.

See Also