Search code examples
wpfvalidationwpfdatagrid

How to validate data in DataGrid when it is bound to a DataTable?


I am not able to figure out a way to validate user input in a DataGrid control when it is bound to a DataTable. The issues I see are:

  1. I can't add custom validation rules to the data source i.e. DataTable because the only constraints that can be added to it are UniqueConstraint and ForeignKeyConstraint.
  2. Overriding the CellEditEnding event in the grid, and then setting the property e.cancel = true - where argument e is of type DataGridCellEditEndingEventArgs - on invalid input detection doesn't help one bit because the invalid value is anyway assigned to the underlying DataTable.

The input validation I am after are related to business rules, like a decimal value can't be negative, and another value has to be in the range say 10-25. Surely, there must be some way to enforce these rules.

Thanks.


Solution

  • you can validate a datatable in ColumnChanging Event and use SetColumnError