0
votes

I'm trying to sort a DataTable that contains some dates and values. I pass the DataTable information to a DataGridView and sort the data, then try to pass it back.

The below code runs successfully, but does not produce any difference:

Form1.DataGridView1.DataSource = ChartTable
Form1.DataGridView1.Sort(Form1.DataGridView1.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
ChartTable = CType(Form1.DataGridView1.DataSource, DataTable).Copy()
ChartTable = ChartTable.DefaultView.ToTable

For i = 0 To ChartTable.Rows.Count - 1
    Debug.Print("ChartTable = " & ChartTable.Rows(i)(0) & ", DataGrid = " & Form1.DataGridView1.Rows(i).Cells(0).Value)
Next 

Here's the Output from the Debug.Print

ChartTable = 30/12/15, DataGrid = 27/10/15
ChartTable = 27/10/15, DataGrid = 19/11/15
ChartTable = 29/12/15, DataGrid = 22/12/15
ChartTable = 22/12/15, DataGrid = 29/12/15
ChartTable = 19/11/15, DataGrid = 30/12/15

The ChartTable (which is the DataTable) is still in it's original un-sorted state.

Am I missing something?

2
You want to sort datas in the query or allow the user to sort the DataGridView? - nbadaud
The user can't see the DataGridView, it's only being used to try and provide sorting - LBPLC
Does it sort your datagridview if you create a button with DataGridView1.Sort(Form1.DataGridView1.Columns(0), System.ComponentModel.ListSortDirection.Ascending) ? - nbadaud
Yes, the Output from the Debug.Print shows that the datagridview has been sorted in ascending order - LBPLC
Quote : "First of all the DataTable object is detached from DataGridView even if you bind it to DataSource, that is, if you change your DataGridView it will not affect your DataTable." Check this link, for full answer. - nbadaud

2 Answers

2
votes

I think that it's because Datagridview sorts the data for himself, not doing changes to his datasource. When you copy the datasource, are copying the non-sorted datatable.

To do what you want, i think you may have to do a process to get row by row of the datagridview to the datatable.

But, in my opinion, it should be a lot better (and faster) if you sort the info before to fill the datatable.

0
votes

You can use this code to sort your data table:

    Dim filterExp As String = ""
    Dim sortExp As String = dt.Columns.Item(0).ColumnName
    Dim i As Integer
    Dim dtrow() As DataRow
    dtrow = dt.Select(filterExp, sortExp, DataViewRowState.CurrentRows)

    For i = 0 To dtrow.Length - 1
       DataGridView1.Rows.Add(dtrow(i)(dt.Columns.Item(0).ColumnName))
    Next