How to sort rows in DataTable

Hello!

I have a DataGridView which is binded to DataTable. For database I simply use XML file. This xml file is updated (via DataTable) according to changed which are made on DataGridView. Application also works in other way - data is loaded from xml file into DataTable and populates the DataGridView. My problem is that I would like to sort data (rows) in my own way. I saw DataGridView has a Sort() function. But it is binded to DataTable so sorting rows in DataGridView is not possible. Then I tried to sort rows in DataTable but it has no sorting function... Sorting data in XML file would be to complicated...
Does anybody knows the way of sorting rows (for example in DataTable) or any other way
Thanks for any idea,
Ziga


Answer this question

How to sort rows in DataTable

  • PraveenL

    Hi Ziga,

    you could use a BindingSource control and bind your DataGridView to your DataTable through it. BindingSource has a Sort property which will help you sort the data:

    bindingSource.DataSource = table;
    dataGridView.DataSource = bindingSource;
    bindingSource.Sort = "Location";

    Alternativly, you can just use a DataView:

    DataView view = new DataView(table);
    view.Sort = "Location";
    dataGridView.DataSource = view;

    or change the DataTable's DefaultView:

    table.DefaultView.Sort = "Location";

    Andrej



  • AndyQ

    Thanx! That would be an option. But problem is I would like to sort data depending on one column (for example "Location") but not in alphabetical order... For example first section of rows in grid should be reserved for NewYork, second section for Los Angeles and third section fot Atlanta...

  • GMagana

    Thanx, that s a good idea!

  • bitbonk

    Take a look at DataGridView FAQ for some examples of DataGridView custom sorting.

    Andrej



  • loopool

    You can add a table with two columns City and SortOrder and put for your example three rows with data NewYork, 0 ; Los Ngeles, 1 ; Athlanta, 3. Then datatable will be result of join of your main table and this one by column City and you will Order by SortOrder.

  • How to sort rows in DataTable