Validate and Save Data
- 2 minutes to read
This topic explains different strategies you can use to validate user input in edit forms.
Validate Data at the Source Level
DataGridView includes APIs to help you validate data before it is locally saved at the database level. This allows you to keep database constraints and ensure that the database update does not fail because of a bad internet connection.
Handle the ValidateAndSave event to validate input values before the DataGridView commits them to the data source object.
The DataGridView runs validation mechanisms after a user taps the Save button in the edit form in a built-in detail form, or after you call the DetailEditFormViewModel.Save() method for a custom form.
In the ValidateAndSave
event handler, if you set the ValidateItemEventArgs.IsValid property to false
, DataGridView does not apply value changes to the source item.
The following example shows an alert message if the input value in the Quantity edit box does not comply with predefined requirements:
private void grid_ValidateAndSave(object sender, ValidateItemEventArgs e) {
if (e.DataChangeType == DataChangeType.Add) {
Order order = (Order)e.Item;
if (order.Quantity <= 0) {
((NavigationPage)Application.Current.MainPage).CurrentPage.DisplayAlert("Alert message", "Quantity cannot be less than or equal to 0.", "Cancel", "Discard");
e.IsValid = false;
}
}
}
If you want to manually commit changes to the ItemsSource, disable the ValidateItemEventArgs.AutoUpdateItemsSource property. After you commit changes to the source, call the RefreshData or RefreshRow method to make the DataGridView re-fetch source data.
void OnValidateAndSave(object sender, ValidateItemEventArgs e) {
var item = (Issue)e.Item;
try {
if(e.DataChangeType == DataChangeType.Add || e.DataChangeType == DataChangeType.Edit) {
var context = (IssuesContext)e.Context;
context.SaveChanges();
} else if(e.DataChangeType == DataChangeType.Delete) {
using(var context = new IssuesContext()) {
var issue = new Issue() { Id = item.Id };
context.Entry(issue).State = EntityState.Deleted;
context.SaveChanges();
}
}
} catch(Exception exception) {
e.IsValid = false;
await AppShell.Current.DisplayAlert("Error when saving changes", exception.Message, "OK");
return;
}
e.AutoUpdateItemsSource = false;
var itemsSource = (ObservableCollection<Issue>)collectionView.ItemsSource;
if(e.Action == DataChangeType.Edit) {
itemsSource[e.SourceIndex] = item;
return;
}
if(e.Action == DataChangeType.Add) {
itemsSource.Add(e.Item);
return;
}
if(e.Action == DataChangeType.Delete) {
itemsSource.RemoveAt(e.SourceIndex);
return;
}
}
Validate Data at the DataFormView Level
Since built-in forms use DataFormView, you can use this component’s API to validate user input.
For more information, refer to the following help topic: Validate User Input in Data Form for .NET MAUI.