Alice Guo
Alice Guo

Reputation: 35

How to get correct index in datagrid after double clicking heading to sort?

My current problem is: I get a datagrid at first, then when I select a row, I'll have a index, with that index, I could use convert datagrid to DataTable DataTable.rows[idx]["Column Name"] to get the value. When I double click the header again, everything is resorted, at the backend, the datagrid is not refreshed, when I get the new index, it will go to the old datagrid to find the new index value. I don't want to refresh the datatable every time, too much calculation.

Forexample, the first row, after resorting, the index become 4, the system will go to use DataTable.rows[4]["Column Name"] to get a value, which isn't the value I want.

Thank you so much!

Upvotes: 0

Views: 447

Answers (2)

Alice Guo
Alice Guo

Reputation: 35

Currently I convert the datagrid to datatable each time when the selection changed.

        private void DataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var idx = DataGrid1.SelectedIndex;


        _dtDataGrid = ((DataView)DataGrid1.ItemsSource).ToTable();



        if (idx < 0) idx = 0;
        BindAmDetail(_dtDataGrid, idx);
        if (DataGrid1.SelectedItem != null) DataGrid1.ScrollIntoView(DataGrid1.SelectedItem);


    }

Upvotes: 0

Manigandan Dorairaj
Manigandan Dorairaj

Reputation: 108

The SelectedIndex property gets changed only when a row is selected by user's action or by code. So even after sorting, the property's value doesn't get changed. You can explicitly reset it to -1 (to select nothing) or 0 (for selecting the first row) in the SortCommand event.

Upvotes: 0

Related Questions