Search code examples
c#wpfwpfdatagridselectedindex

Why is setting the selection in WPF datagrid not work?


I have problem on setting the selection on DataGrid. I save the SelectedIndex, but when I want to set it back after some refresh, it doesn't seem to work.

int index = dgrid.SelectedIndex;
//some code including resresh of the DG
dgrid.SelectedIndex = index;

I have some code which triggers on SelectionChanged, which actually fires.

private void dgrid_selection_change(object sender, SelectionChangedEventArgs e)
    {
        try
        {
            string ID = 
(dgrid.SelectedCells[0].Column.GetCellContent(dgrid.SelectedItem) as TextBlock).Text;

//some code that shall execute...

When I try to get some data from it, the selection is null.

What am I doing wrong?


Solution

  • Didn't figure out why it is not working, but found a solution. Just replaced

    string ID = (dgrid.SelectedCells[0].Column.GetCellContent(dgrid.SelectedItem) as TextBlock).Text;
    

    to

    string ID= (dgrid.SelectedItem as DataRowView)["ID"].ToString(); 
    

    and it works.