3
votes

Okay, this is driving me nuts. I've spent hours trying to figure out what should be a simple solution, but I'm having no luck.

I have a [WPF Toolkit] DataGrid on an XAML page that has a DataTable as its ItemsSource. I also have a button on my page that gets the DataGrid's SelectedIndex (selected row) and uses it as a variable in a function that reads the bound DataTable's row at that index and returns a value. Everything works fine until I click a column header to sort it. It sorts the DataGrid but does not sort the DataTable with it, so my SelectedIndex has changed but the index of the DataTable has not, thus it returns the wrong value.

I've looked for Column Header click events - no luck; I tried to get the header of the column by which the grid is currently sorted - nada; I tried to use a "Click" EventSetter on the DataGridTextColumn template - not supported.

I'm completely at a loss. If WPF is supposed to be an improvement over Windows Forms, why has some of the simple functionality been removed? (It's also dumb that you have to bind data just to add rows, just saying.) I can use a Windows Forms DataGrid and won't have any trouble, but then I can't style it.

Maybe I'm not performing the check properly or something...? Below is my retrieval/output code. Anyone have any ideas??? Your help will be greatly appreciated!

DataRow selectedRow = my_data.Tables[0].Rows[my_grid.SelectedIndex];
MessageBox.Show(selectedRow["ItemName"]);
1
Please show an excerpt of the XAML you are using. I am a WPF nub but it could be a matter of you not using a TwoWay binding.RedDeckWins
I believe the Two Way binding is taken care of automatically with the ItemsSource property. biju's answer below provided exactly what I needed, but I appreciate your response anyway! Thank you.Randy Cleary

1 Answers

9
votes

The sorting is applied to the DefaultView of the datatable.So it will not be applied to the Datatable directly.To access the sorted table use

DataTable.DefaultView.ToTable()