Home > Blockchain >  C# - How to validate data in C1DataGrid?
C# - How to validate data in C1DataGrid?

Time:01-26

I have a C1DataGrid with one column and I want to be able to validate the data when I commit a new row in the grid.

So far I tried to throw an exception in the setter of this property. This validates the data while I am typing it in the text box correctly (throws an exception), but I am still able to commit the new row.

Furthermore I would like to only do the validation when I commit my new row and not after every new character I write.

Could someone show me how to do it? Many thanks!

CodePudding user response:

You should implement inotifydataerrorinfo

https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo?view=net-7.0

The easy way to do that is use the community mvvm toolkit

Inherit the viewmodel you're using for each item from Observablevalidator Add your validation attribute(s), or custom validation

https://learn.microsoft.com/en-us/windows/communitytoolkit/mvvm/observablevalidator

You could then check IsValid or HasErrors in the CommittingEdit event and stop it committing

https://www.grapecity.com/componentone/docs/wpf/online-datagrid/C1.WPF.DataGrid.4.5.2~C1.WPF.DataGrid.C1DataGrid~CommittingEdit_EV.html

The datagrid itself might automatically check HasErrors, I'm not familiar with C1Datagrid

Bear in mind that what inotifydataerrorinfo is doing is telling you your viewmodel has bad data in it. You then have to do something about it. Revert the change from a cached version or something.

It is because of this that I would usually keep any "original" OK data. Have the user edit a copy of any item separately from that and then only replace that original item ( or add a new one to a collection ) if it is definitely valid.

With a datagrids where the user can just edit like it's excel, you're better stopping them actually entering any bad data.

I only use this for quite simplistic scenarios like only entering integers or some such. The way I handle that is with an attached behavior which will essentially just not let the user type or paste invalid data in. There are obvious inherent limitations to this approach.

Another thing to consider is a binding ValidationRule. https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-implement-binding-validation?view=netframeworkdesktop-4.8

These work as the user enters and will stop invalid data transferring to the viewmodel property. You still have bad data in the datagrid though. So the user types bad stuff, the cell should respond and turn red or whatever. But you still have your bad stuff there in your view.

  • Related