Set Selected DataGridRow in code-behind

Dec 9, 2008 at 9:54 AM
Hello!

How can i set a DataGridRow selected in code-behind ?
I do know the index of the Row with the use of.

protected int FindRowIndex(DataGridRow row) {
            DataGrid dataGrid =
                ItemsControl.ItemsControlFromItemContainer(row)
                as DataGrid;
  int index = dataGrid.ItemContainerGenerator.IndexFromContainer(row);
            return index;
        }

But if i set dataGrid.SelectedIndex = idx; the row -selection isnt changed visually - What else do I have to call ?

Thx for any tip
Coordinator
Dec 9, 2008 at 1:36 PM
What about setting DataGrid.SelectedItem to the row.Item instead.  That should visually change selection.
Dec 9, 2008 at 1:45 PM
Hi vinsibal!
Thx for the quick response!
Unfortunately the visually change does not seem to work
I try to set it in RowEditEndingMethod. 
I do a Validation of the Grid-Row where I check some values, and if the validation fails, i want to stay in the 
row!

public void RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) {
            if (e.Cancel) return;
            if (e.EditAction == DataGridEditAction.Commit) {
                e.Cancel = CheckRowIncomplete((DataGrid)sender, e.Row);
                if (e.Cancel) {
                    DataGridCell l_cell = GetCell(auftraegeGrid,e.Row, 0);
                     ...
                    auftraegeGrid.SelectedItem = _lastAuftragRow.Item;
                }
            }
        }

Thx for any more tipps
Robert
Dec 9, 2008 at 2:42 PM
Have you tried using row level validation? See for example http://www.codeplex.com/wpf/Thread/View.aspx?ThreadId=41568
Dec 9, 2008 at 4:08 PM
I'm sorry, but I can't see an example.

Could you please give me a hint how I can do the row level validation you mentioned?


Coordinator
Dec 9, 2008 at 5:16 PM
The sample on this post, http://blogs.msdn.com/vinsibal/archive/2008/10/22/wpf-datagrid-and-the-wpftoolkit-have-released.aspx, shows an example of how to use row level validation.

By the way, with your current implementation, I believe selection is not working b/c selection needs to be updated after the row edit has ended and not while it is ending.  Using row-level validation is the solution you should use but if you are in a situation where you want to update selection when a row edit is complete you can listen to the RowEditEnding event and use a Dispatcher.BeginInvoke operation with a lower priority such as DispatcherPriority.Background to update the selection.