| layout | post |
|---|---|
| title | Data Validation in WinUI DataGrid control | Syncfusion® |
| description | Learn here all about Data Validation support in Syncfusion® WinUI DataGrid(SfDataGrid) control and more. |
| platform | winui |
| control | DataGrid |
| documentation | ug |
SfDataGrid allows you to validate the data and display hints in case of validation is not passed. In case of invalid data, error icon is displayed at the top right corner of GridCell. When mouse over the error icon, error information will be displayed in tooltip.
Built-in validations through INotifyDataErrorInfo and Data annotation attributes, can be enabled by setting SfDataGrid.DataValidationMode or GridColumn.DataValidationMode properties.
GridColumn.DataValidationMode takes priority than SfDataGrid.DataValidationMode.
GridValidationMode.InView- displays error icons and tips alone.GridValidationMode.None- disables built-in validation support.
SfDataGrid provides support to validate the data based on INotifyDataErrorInfo.
You can validate the data by inheriting the INotifyDataErrorInfo interface in model class.
{% tabs %} {% highlight c# %} public class Employee : INotifyDataErrorInfo { private int _EmployeeID;
/// <summary>
/// Gets or sets the employee ID.
/// </summary>
/// <value>The employee ID.</value>
public int EmployeeID
{
get
{
return this._EmployeeID;
}
set
{
this._EmployeeID = value;
}
}
private List<string> errors = new List<string>();
public IEnumerable<object> GetErrors(string propertyName)
{
if (!propertyName.Equals("EmployeeID"))
return null;
if (this.EmployeeID == 1003 || this.EmployeeID == 1004)
errors.Add("Delivery not available for " + this.EmployeeID);
return errors;
}
[Display(AutoGenerateField = false)]
public bool HasErrors
{
get
{
if (this.EmployeeID == 1003 || this.EmployeeID == 1004)
return true;
return false;
}
}
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
} {% endhighlight %} {% endtabs %}
Enable built-in validation support by setting SfDataGrid.DataValidationMode or GridColumn.DataValidationMode property to InView.
{% tabs %} {% highlight xaml %} <dataGrid:SfDataGrid x:Name="sfDataGrid" DataValidationMode="InView" AutoGenerateColumns="True" ItemsSource="{Binding Employees}"/> {% endhighlight %} {% highlight c# %} this.sfDataGrid.DataValidationMode = GridValidationMode.InView; {% endhighlight %} {% endtabs %}
You can validate the data using data annotation attributes by setting SfDataGrid.DataValidationMode or GridColumn.DataValidationMode property to InView.
The numeric type like int, double, decimal properties can be validated using Range attributes.
{% tabs %} {% highlight c# %}
private int _EmployeeID;
///
private double _Salary;
///
{% endhighlight %} {% endtabs %}
The string type property can be validated using Required, String Length attributes
{% tabs %} {% highlight c# %} private string _Name;
///
private string _Title;
///
{% endhighlight %} {% endtabs %}
The data that has heterogeneous type (combination of number, special character) can be validated using RegularExpressions.
{% tabs %} {% highlight c# %}
private string _Title; ///
public string Title { get { return this._Title; } set { this._Title = value; } }
{% endhighlight %} {% endtabs %}
You can validate the cells using CurrentCellValidating event when the cell is edited. CurrentCellValidating event occurs when the edited cells tries to commit the data or lose the focus. DataGrid will not allow user to edit other cells if validation failed.
CurrentCellValidatingEventArgs provides information to CurrentCellValidating event for validating the cell. CurrentCellValidatingEventArgs.OriginalSender returns the DataGrid fired this event.
CurrentCellValidatingEventArgs.NewValue returns the edited value and you can set the validation status using CurrentCellValidatingEventArgs.IsValid property.
{% tabs %} {% highlight c# %} this.sfDataGrid.CurrentCellValidating += SfDataGrid_CurrentCellValidating;
private void SfDataGrid_CurrentCellValidating(object sender, CurrentCellValidatingEventArgs e) { if (e.NewValue.ToString().Equals("1004")) { e.IsValid = false; e.ErrorMessage = "EmployeeID 1004 cannot be passed"; } }
{% endhighlight %} {% endtabs %}
SfDataGrid.CurrentCellValidated event triggered when the cell has finished validating with valid data.
{% tabs %} {% highlight c# %} this.sfDataGrid.CurrentCellValidated += SfDataGrid_CurrentCellValidated;
private void SfDataGrid_CurrentCellValidated(object sender, CurrentCellValidatedEventArgs e) {
}
{% endhighlight %} {% endtabs %}
You can validate the row using RowValidating event when the cell is edited. The RowValidating event occurs when the edited cells tries to commit the row data or lose the focus. DataGrid will not allow user to edit other rows if validation failed.
RowValidatingEventArgs provides information to RowValidating event for validating row. RowValidatingEventArgs.OriginalSender returns the DataGrid fired this event.
RowValidatingEventArgs.RowData returns the edited value and you can set the validation status using RowValidatingEventArgs.IsValid property.
{% tabs %} {% highlight c# %} this.sfDataGrid.RowValidating += SfDataGrid_RowValidating;
private void SfDataGrid_RowValidating(object sender, RowValidatingEventArgs e) { var data = e.RowData.GetType().GetProperty("Name").GetValue(e.RowData);
if (data.ToString().Equals("Marvin Allen"))
{
e.IsValid = false;
e.ErrorMessages.Add("Name", "Marvin Allen cannot be passed");
}
}
{% endhighlight %} {% endtabs %}
SfDataGrid.RowValidated event triggered when the row has finished validating with valid row data.
{% tabs %} {% highlight c# %} this.sfDataGrid.RowValidated += SfDataGrid_RowValidated;
private void SfDataGrid_RowValidated(object sender, RowValidatedEventArgs e) {
} {% endhighlight %} {% endtabs %}
You can customize the error icon by editing GridCell style.
You can change the validation error template shape of the GridCell by changing the Data property of the path in the PART_InValidCellBorder of GridCell. And need to add the DataGrid ThemeDictionary in ResourcesDictionary.
{% tabs %} {% highlight xaml %}
<Border Margin="4,4,-4,-4"
Background="Transparent"
CornerRadius="5" />
<Border Margin="3,3,-3,-3"
Background="Transparent"
CornerRadius="4" />
<Border Margin="2,2,-2,-2"
Background="Transparent"
CornerRadius="3" />
<Border Margin="1,1,-1,-1"
Background="Transparent"
CornerRadius="2" />
<Border Background="{ThemeResource SystemFillColorCritical}" CornerRadius="2" />
<Border CornerRadius="2" BorderBrush="{ThemeResource SystemFillColorCritical}">
<TextBlock MaxWidth="250"
Margin="8,4,8,4"
FontFamily="{ThemeResource SyncfusionDataGridFontFamily}"
FontSize="{ThemeResource SyncfusionBodyFontSize}"
FontWeight="{ThemeResource SyncfusionDataGridFontWeight}"
Foreground="{ThemeResource SyncfusionDataGridCellValidationToolTipErrorForeground}"
Text="{TemplateBinding Tag}"
TextWrapping="Wrap"
HighContrastAdjustment="None"
UseLayoutRounding="false" />
</Border>
</Grid>
{% endhighlight %} {% endtabs %}
You can change the validation error template color of the GridCell by changing the Fill property of the path in the PART_InValidCellBorder of GridCell.
{% tabs %} {% highlight xaml %}
<Border Margin="4,4,-4,-4"
Background="Transparent"
CornerRadius="5" />
<Border Margin="3,3,-3,-3"
Background="Transparent"
CornerRadius="4" />
<Border Margin="2,2,-2,-2"
Background="Transparent"
CornerRadius="3" />
<Border Margin="1,1,-1,-1"
Background="Transparent"
CornerRadius="2" />
<Border Background="{ThemeResource SystemFillColorCritical}" CornerRadius="2" />
<Border CornerRadius="2" BorderBrush="{ThemeResource SystemFillColorCritical}">
<TextBlock MaxWidth="250"
Margin="8,4,8,4"
FontFamily="{ThemeResource SyncfusionDataGridFontFamily}"
FontSize="{ThemeResource SyncfusionBodyFontSize}"
FontWeight="{ThemeResource SyncfusionDataGridFontWeight}"
Foreground="{ThemeResource SyncfusionDataGridCellValidationToolTipErrorForeground}"
Text="{TemplateBinding Tag}"
TextWrapping="Wrap"
HighContrastAdjustment="None"
UseLayoutRounding="false" />
</Border>
</Grid>
{% endhighlight %} {% endtabs %}
You can customize the error tip by editing the style of ValidationToolTipTemplate. Get the style of ValidationToolTipTemplate by editing the GridCell style.
You can change the error tip background color by setting Background property of the border in ValidationToolTipTemplate. The error tip foreground color can be changed by setting Foreground property of the TextBlock in ValidationToolTipTemplate.
{% tabs %} {% highlight xaml %} <Grid.RenderTransform> </Grid.RenderTransform> <VisualStateManager.VisualStateGroups> <VisualStateGroup.Transitions> <DoubleAnimation.EasingFunction> </DoubleAnimation.EasingFunction> </VisualStateGroup.Transitions> </VisualStateManager.VisualStateGroups>
<Border Margin="4,4,-4,-4"
Background="Transparent"
CornerRadius="5" />
<Border Margin="3,3,-3,-3"
Background="Transparent"
CornerRadius="4" />
<Border Margin="2,2,-2,-2"
Background="Transparent"
CornerRadius="3" />
<Border Margin="1,1,-1,-1"
Background="Transparent"
CornerRadius="2" />
<Border Background="{ThemeResource SystemFillColorCritical}" CornerRadius="2" />
<Border CornerRadius="2" Background="Orange" BorderBrush="{ThemeResource SystemFillColorCritical}">
<TextBlock MaxWidth="250"
Margin="8,4,8,4"
FontFamily="{ThemeResource SyncfusionDataGridFontFamily}"
FontSize="{ThemeResource SyncfusionBodyFontSize}"
FontWeight="{ThemeResource SyncfusionDataGridFontWeight}"
Foreground="Black"
Text="{TemplateBinding Tag}"
TextWrapping="Wrap"
HighContrastAdjustment="None"
UseLayoutRounding="false" />
</Border>
</Grid>
{% endhighlight %} {% endtabs %}
SfDataGrid support to show the error icon in GridRowHeaderCell based on INotifyDataErrorInfo.HasErrors property.
You can show the error information in row header by setting INotifyDataErrorInfo.HasErrors. By default error message Row Containing Error will be displayed. You can change this by changing RowErrorMessage in the resx file.
{% tabs %} {% highlight c# %} [Display(AutoGenerateField = false)] public bool HasErrors { get { if (this.EmployeeID == 1003 || this.EmployeeID == 1004) return true; return false; } }
{% endhighlight %} {% endtabs %}
Master-Details View allows you to validate the bound data is valid or not.
You can do both built-in and custom validation of data in DetailsViewDataGrid.
You can validate the bound data based on INotifyDataErrorInfo or Data Annotation attributes by setting DataValidationMode property of GridViewDefinition.DataGrid.
{% tabs %}
{% highlight xaml %}
<dataGrid:SfDataGrid x:Name="sfDataGrid"
AutoGenerateColumns="True"
ItemsSource="{Binding OrdersDetails}">
dataGrid:SfDataGrid.DetailsViewDefinition
<dataGrid:GridViewDefinition RelationalColumn="OrderDetails">
dataGrid:GridViewDefinition.DataGrid
<dataGrid:SfDataGrid x:Name="firstLevelDetailsViewGrid"
AutoGenerateColumns="True"
DataValidationMode="InView"/>
</dataGrid:GridViewDefinition.DataGrid>
</dataGrid:GridViewDefinition>
</dataGrid:SfDataGrid.DetailsViewDefinition>
</dataGrid:SfDataGrid>
{% endhighlight %}
{% endtabs %}
When the relation is auto-generated, the data can be validated by setting DataValidationMode property to GridViewDefinition.DataGrid in AutoGeneratingRelations event handler.
{% tabs %} {% highlight c# %} sfDataGrid.AutoGenerateRelations = true;
sfDataGrid.AutoGeneratingRelations += SfDataGrid_AutoGeneratingRelations;
private void SfDataGrid_AutoGeneratingRelations(object sender, AutoGeneratingRelationsArgs e) { e.GridViewDefinition.DataGrid.DataValidationMode = GridValidationMode.InView; }
{% endhighlight %} {% endtabs %}
Master-Details View support to validate the cells and rows using CurrentCellValidating and RowValidating events.
You can validate the cells using CurrentCellValidating event of GridViewDefinition.DataGrid when the cell is edited. CurrentCellValidating event occurs when the edited cells tries to commit the data or lose the focus.
{% tabs %} {% highlight xaml %} <dataGrid:SfDataGrid x:Name="sfDataGrid" AutoGenerateColumns="True" DataValidationMode="InView" NavigationMode="Cell" ItemsSource="{Binding OrdersDetails}"> dataGrid:SfDataGrid.DetailsViewDefinition <dataGrid:GridViewDefinition RelationalColumn="OrderDetails"> dataGrid:GridViewDefinition.DataGrid <dataGrid:SfDataGrid x:Name="firstLevelDetailsViewGrid" AutoGenerateColumns="True" CurrentCellValidating="FirstLevelDetailsViewGrid_CurrentCellValidating"> </dataGrid:SfDataGrid> </dataGrid:GridViewDefinition.DataGrid> </dataGrid:GridViewDefinition> </dataGrid:SfDataGrid.DetailsViewDefinition> </dataGrid:SfDataGrid> {% endhighlight %} {% endtabs %}
{% tabs %} {% highlight c# %} this.firstLevelDetailsViewGrid.CurrentCellValidating += FirstLevelDetailsViewGrid_CurrentCellValidating;
private void FirstLevelDetailsViewGrid_CurrentCellValidating(object sender, CurrentCellValidatingEventArgs e) { if (e.NewValue.ToString().Equals("FRANS")) { e.IsValid = false; e.ErrorMessage = "Order not delivered for the ID FRANS"; } }
{% endhighlight %} {% endtabs %}
CurrentCellValidated event of GridViewDefinition.DataGrid triggered when the cell has finished validating with valid data
{% tabs %} {% highlight xaml %} <dataGrid:SfDataGrid x:Name="sfDataGrid" AutoGenerateColumns="True" DataValidationMode="InView" NavigationMode="Cell" ItemsSource="{Binding OrdersDetails}" AllowEditing="True"> dataGrid:SfDataGrid.DetailsViewDefinition <dataGrid:GridViewDefinition RelationalColumn="OrderDetails"> dataGrid:GridViewDefinition.DataGrid <dataGrid:SfDataGrid x:Name="firstLevelDetailsViewGrid" AutoGenerateColumns="True" CurrentCellValidated="FirstLevelDetailsViewGrid_CurrentCellValidated" AllowEditing="True" DataValidationMode="InView"> </dataGrid:SfDataGrid> </dataGrid:GridViewDefinition.DataGrid> </dataGrid:GridViewDefinition> </dataGrid:SfDataGrid.DetailsViewDefinition> </dataGrid:SfDataGrid>
{% endhighlight %} {% endtabs %}
{% tabs %} {% highlight c# %} this.firstLevelDetailsViewGrid.CurrentCellValidated += FirstLevelDetailsViewGrid_CurrentCellValidated;
private void FirstLevelDetailsViewGrid_CurrentCellValidated(object sender, CurrentCellValidatedEventArgs e) {
} {% endhighlight %} {% endtabs %}
When the relation is auto-generated, you can wire the CurrentCellValidating and CurrentCellValidated events for AutoGeneratingRelations.GridViewDefinition.DataGrid in AutoGeneratingRelations event handler.
{% tabs %} {% highlight c# %} sfDataGrid.AutoGenerateRelations = true;
sfDataGrid.AutoGeneratingRelations += SfDataGrid_AutoGeneratingRelations;
private void SfDataGrid_AutoGeneratingRelations(object sender, AutoGeneratingRelationsArgs e) { e.GridViewDefinition.DataGrid.CurrentCellValidating += FirstLevelDetailsViewGrid_CurrentCellValidating; e.GridViewDefinition.DataGrid.CurrentCellValidated += FirstLevelDetailsViewGrid_CurrentCellValidated; }
{% endhighlight %} {% endtabs %}
You can validate the row using RowValidating event of GridViewDefinition.DataGrid when the cell is edited.
The RowValidating event occurs when edited cells tries to commit the row data or lose the focus.
{% tabs %}
{% highlight xaml %}
<dataGrid:SfDataGrid x:Name="sfDataGrid"
AutoGenerateColumns="True"
DataValidationMode="InView"
ItemsSource="{Binding OrdersDetails}">
dataGrid:SfDataGrid.DetailsViewDefinition
<dataGrid:GridViewDefinition RelationalColumn="OrderDetails">
dataGrid:GridViewDefinition.DataGrid
<dataGrid:SfDataGrid x:Name="firstLevelDetailsViewGrid"
AutoGenerateColumns="True"
AllowEditing="True"
DataValidationMode="InView"
RowValidating="FirstLevelDetailsViewGrid_RowValidating">
</dataGrid:SfDataGrid>
</dataGrid:GridViewDefinition.DataGrid>
</dataGrid:GridViewDefinition>
</dataGrid:SfDataGrid.DetailsViewDefinition>
</dataGrid:SfDataGrid>
{% endhighlight %}
{% endtabs %}
{% tabs %}
{% highlight c# %}
this.firstLevelDetailsViewGrid.RowValidating += FirstLevelDetailsViewGrid_RowValidating;
private void FirstLevelDetailsViewGrid_RowValidating(object sender, RowValidatingEventArgs e) { var data = e.RowData.GetType().GetProperty("CustomerID").GetValue(e.RowData); if (data.ToString().Equals("FRANS")) { e.IsValid = false; e.ErrorMessages.Add("CustomerID", "Order not delivered for the ID FRANS"); } }
{% endhighlight %} {% endtabs %}
RowValidated event of GridViewDefinition.DataGrid event triggered when the row has finished validating with valid row data.
{% tabs %}
{% highlight xaml %}
<dataGrid:SfDataGrid x:Name="sfDataGrid"
AutoGenerateColumns="True"
ItemsSource="{Binding OrdersDetails}">
dataGrid:SfDataGrid.DetailsViewDefinition
<dataGrid:GridViewDefinition RelationalColumn="OrderDetails">
dataGrid:GridViewDefinition.DataGrid
<dataGrid:SfDataGrid x:Name="firstLevelDetailsViewGrid"
AutoGenerateColumns="True"
AllowEditing="True"
DataValidationMode="InView"
RowValidated="FirstLevelDetailsViewGrid_RowValidated">
</dataGrid:SfDataGrid>
</dataGrid:GridViewDefinition.DataGrid>
</dataGrid:GridViewDefinition>
</dataGrid:SfDataGrid.DetailsViewDefinition>
</dataGrid:SfDataGrid>
{% endhighlight %}
{% endtabs %}
{% tabs %}
{% highlight c# %}
this.firstLevelDetailsViewGrid.RowValidated += FirstLevelDetailsViewGrid_RowValidated;
private void FirstLevelDetailsViewGrid_RowValidated(object sender, RowValidatedEventArgs e) {
}
{% endhighlight %} {% endtabs %}
When the relation is auto-generated, you can wire the RowValidating and RowValidated events for AutoGeneratingRelations.GridViewDefinition.DataGrid in AutoGeneratingRelations event handler.
{% tabs %} {% highlight c# %} sfDataGrid.AutoGenerateRelations = true;
sfDataGrid.AutoGeneratingRelations += SfDataGrid_AutoGeneratingRelations;
private void SfDataGrid_AutoGeneratingRelations(object sender, AutoGeneratingRelationsArgs e) { e.GridViewDefinition.DataGrid.RowValidating += FirstLevelDetailsViewGrid_RowValidating; e.GridViewDefinition.DataGrid.RowValidated += FirstLevelDetailsViewGrid_RowValidated; }
{% endhighlight %} {% endtabs %}
- Non editable columns will not support custom validation.
CurrentCellValidatingevent will not triggered for GridTemplateColumn and GridUnboundColumn.




