How to: Sort Data in DataGridView Controls

The DataGridView control provides automatic sorting, so that user can manually sort any column in the control. You can control whether a column can be sorted by setting the SortMode property of the DataGridViewColumn. You can also programmatically sort a column.

To sort data in a DataGridView control

  1. Add a DataGridView control by using the Customers table from the Northwind database, as described in How to: Display Data by Using DataGridView Controls.

  2. Click the ellipsis (…) button next to the Columns property.

    The Edit Columns dialog box opens.

  3. In the Edit Columns dialog box, select the first column, and then in the Bound Column Properties window, set the SortMode property to Programmatic.

  4. Select the second column and set its SortMode property to NotSortable.

  5. Select the third column and set its SortMode property to Automatic.

  6. Click OK to close the dialog box.

  7. Drag a Button control from the Toolbox under the DataGridView control.

  8. Double-click the button to add the default event handler in code view, and add the following code.

    this.customersDataGridView.Sort(this.dataGridViewTextBoxColumn1, ListSortDirection.Descending);
    

    This code sorts the first column in the DataGridView control in descending order.

  9. Press F5 to run the code.

  10. When the DataGridView control displays the data, click the third column, and verify that the data sorts.

  11. Click the second column, and verify that the data does not sort.

  12. Click the button and verify that the data sorts the first column in descending order.

See Also

Tasks

How to: Display Data by Using DataGridView Controls

How to: Hide Columns in DataGridView Controls

Other Resources

Accessing and Displaying Data

Sorting Data in the Windows Forms DataGridView Control