Moving rows up and down, adding and deleting rows

Jan 7, 2009 at 7:49 PM
I have buttons for "Up", "Down", "Add" and "Delete" in the same Control as the DataGrid resides.

I use the "Up" and "Down" buttons to move the selected rows up and down.
The "Add" button adds a new row at the bottom, and the "Delete" button deletes the selected rows.

The way I accomplish this, is by modifying the collection that's bound to the DataGrid, and then I call UpdateTarget on the binding expression.

Is this recommended way of getting this kind of behaviour?  Or is there some functionality in the DataGrid I don't know about?

The main reason I'm asking is that I'm getting some strange NullPointerReference exceptions in unit tests after calling one of my "manipulate model" methods.

See for a stack trace (it happens when using the GetRow helper function mentioned in

Jan 7, 2009 at 8:03 PM
Well, in the GetRow() helper thread, vinsibal mentions using dataGrid.Items.Add() so that one can presumably be used to add rows...?

Is it possible to manipulate dataGrid.Items in other ways?  Ie. to move rows and to delete rows?  And if it is, and if it works, is it better or worse than manipulating the model? (and why is it better or worse?)


- Steinar
Jan 7, 2009 at 8:16 PM
I tried implementing the Up and Down buttons by manipulating dataGrid.Items instead of the model.  But then I got the following exception:
System.InvalidOperationException: Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.

And ItemsSource has a data binding on it.

So presumably the correct way (and it also feels like the correct way), is to manipulate the model.

So why am I getting the stack trace referred to earlier in this thread?  Am I missing something?  Isn't calling UpdateTarget sufficient?