views:

512

answers:

1

I have a DataGridView that is bound to a DataTable, is there a way to reorder the rows in the DataGridView and have the changes reflected in the bound DataTable?

+1  A: 

Use a DataView or a BindingSource between the DataTable and the DataGridView, they both have a Sort property :

DataView view = new DataView(table);
view.Sort = "Name ASC, Age Desc";
dataGridView.DataSource = view;

You can also filter the results using the DataView.RowFilter property (or BindingSource.Filter).

The DataGridView will automatically reflect the changes

Thomas Levesque
What if there is no definitive sorting scheme? ie. I want to move the 9th row to the 1st position?
jumpinjackie
Remove the ninth row from the DataTable, and insert it at the first position
Thomas Levesque
- or add a new "Order" column to the DataTable and use it for sorting. Whatever you do, always perform sorting at the DataSource side, not in the DataGridView, or you'll end up hanging yourself ;)
Thomas Levesque