4
votes

Description of application structure:

Language is C# with WPF and MVVM pattern. View is basically a DataGrid for displaying some DataTable values (through ViewModel). User is allowed to add, edit and delete rows from the grid. Some value restrictions apply (no nulls, only numeric, etc...) due to database from where values are retrieved and later inserted back.

Data modifications can be made directly to DataGrid but there is also a separate dialog for editing and adding new rows. A delete button works in a way that ViewModel finds selected DataGrid rows from DataTable, deletes them and changes are updated automatically to DataGrid as they should.

Problem:

So I'm having this problem where user attempts to insert invalid data to DataGrid and red exclamation mark appears to indicate that there is a problem with inserted data (validation error I guess?). If at this point user wishes to start over and selects invalid row for deletion, he is unable to delete that row as it does not exist in the model but only in DataGrid. Attempting to delete invalid DataGridRow directly from DataGrid throws an exception stating that DataGrid is bound to a Model and any modifications should be made there.

Finally question:

How to delete invalid DataGridRow which is not present in model?

1
If the invalid row is not present in the model then there's no way to delete it, but similarly, if it is not there, forcing the DataGrid to re-render the data should only show valid rows. You could try a DataGrid.Items.Refresh() - I'm not certain that this will work, but it's worth a try. - Alex
Thanks for reply. I tried this and got exception stating "'Refresh' is not allowed during an AddNew or EditItem transaction." Apparently invalid data causes Datagrid to get 'stuck' in editing state or something like that. - user3820047
You could try calling CencelEdit() before the refresh. This should clear the edit mode, although with WPF, I have seen some pretty odd behaviour with DataGrids. I gave up on them in the end and rolled my own component using a list box and an object derived from a panel to represent each row. - Alex
Just a thought, did you try selecting the row and delete using the "DELETE" button? - ygoku
@Alex: Tried calling CancelEdit() before refreshing. Same exception as before. - user3820047

1 Answers

0
votes

If you implement MVVM pattern then you don't have to do anything except linking changes in your observablecollection to data layer to connect it to DB.

Also you may define DataGrid as :

<DataGrid ItemsSource="{Binding Items}" SelectedItem="{Binding ActiveItem}" .../>

Then you may react to PropertyChanged events of Items and ActiveItem in your code, kind of

ActiveItem.PropertyChanged += ... 

Hope it helps