Telerik UI for Silverlight

One of the most important features provided by the RadGridView is the data validation. Data Validation enables you to take a complete control of the data entered in your grid's cells.

The purpose of this tutorial is to show you how to validate data using RadGridView. The following cases will be discussed:

Note

The Data Validation is controllable through events. Be sure you are familiar with all validation events exposed by the RadGridView.

For the purpose of this tutorial the following RadGridView declaration will be used. The RadGridView is populated with some sample data.

CopyXAML
<telerik:RadGridView x:Name="radGridView"/>

Setting the mode for the validation

RadGridView exposes a property - ValidatesOnDataErrors that controls the way the data validation, provided by IDataErrorInfo and INotifyDataErrorInfo Interfaces, is performed. It may be set to one of the following values:

  • None - denotes that RadGridView will not perform any validation.
  • InViewMode - denotes that RadGridView will perform validation only in view mode.
  • InEditMode - denotes that RadGridView will perform validation only in edit mode, i.e when the cell is leaving edit mode. In case the RadGridView is initially loaded with incorrect value, no error messages will be displayed.
  • Default - this is the default value. It combines the two previous ones - InViewMode | InEditMode.

Note

Setting the ValidateOnDataErrors property will not affect the UI validation provided by the CellValidating and RowValidating events.

Validating Data on a Cell Level

The cell validation occurs when a GridViewCell is edited and its new data is about to be committed. At this moment a CellValidating event is fired and since the new value is not committed yet to the underlying data object, here is the perfect place for applying a custom UI validation.

Below is an example that validates the OrderNo property of the Order object to be longer than 5 characters.

Attach to the CellValidating event, which is exposed by the RadGridView.

CopyXAML
<telerik:RadGridView x:Name="radGridView" CellValidating="radGridView_CellValidating"/>

Switch to the code-behind and add your custom validation logic in the event handler.

CopyC#
private void radGridView_CellValidating( object sender, Telerik.Windows.Controls.GridViewCellValidatingEventArgs e )
{
    if ( e.Cell.Column.UniqueName == "OrderNO" )
    {
        if ( e.NewValue.ToString().Length < 5 )
        {
            e.IsValid = false;
            e.ErrorMessage = "OrderNO must be longer than five characters.";
        }
    }
}
CopyVB.NET
Private Sub radGridView_CellValidating(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.GridViewCellValidatingEventArgs)
    If e.Cell.Column.UniqueName = "OrderNO" Then
        If e.NewValue.ToString().Length < 5 Then
            e.IsValid = False
            e.ErrorMessage = "OrderNO must be longer than five characters."
        End If
    End If
End Sub

When you try to enter an order number less than five characters the result should be similar to snapshot below.

When you set the e.IsValid property to False, this will cancel the editing process and will return focus to the invalid GridViewCell. After this UI layer validation is successful (e.IsValid is True, which is the default value). Then the Data layer validation occurs. This is the validation which is built-in the business object implementation.

Validating Data on a Property Level

An alternative approach is to use validation on a property level. In this case you need to throw an exception when an incorrect value is about to be set. This results into a binding validation error and GridViewBoundColumnBase editor will enter into invalid state.

CopyC#
public class Order
{
    private string orderNo;
    public string OrderNO
    {
        get
        {
            return this.orderNo;
        }
        set
        {
            if ( value.Length < 5 )
            {
                throw new Exception( "OrderNo should be longer than 5 characters." );
            }
            this.orderNo = value;
        }
    }
}
CopyVB.NET
Public Class Order
    Private m_orderNo As String

    Public Property OrderNO() As String
        Get
            Return Me.m_orderNo
        End Get
        Set(ByVal value As String)
            If value.Length < 5 Then
                Throw New Exception("OrderNo should be longer than 5 characters.")
            End If
            Me.m_orderNo = value
        End Set
    End Property
End Class

Note

An exception of any kind will result as a validation error, and an exception message will appear as an error tooltip.

Validating Data on a Row Level

In the previous examples the data was validated per cell, using the CellValidating event or property validation. You can do the same thing per row, using the RowValidating event. The RowValidating event is a very similar to the CellValidating event. However, instead of getting an individual cell, you are getting an entire row.

Below is an example that validates the OrderNO and Total properties of the Order object.

Attach to the RowValidating event, which is exposed by the RadGridView.

CopyXAML
<telerik:RadGridView RowValidating="radGridView_RowValidating"/>

Switch to the code-behind and add your custom validation logic in the event handler.

CopyC#
private void radGridView_RowValidating( object sender, Telerik.Windows.Controls.GridViewRowValidatingEventArgs e )
{

    Order order = e.Row.DataContext as Order;
    if ( String.IsNullOrEmpty( order.OrderNO ) || order.OrderNO.Length < 5 )
    {
        GridViewCellValidationResult validationResult = new GridViewCellValidationResult();
        validationResult.PropertyName = "OrderNO";
        validationResult.ErrorMessage = "OrderNO is required and must be at least five characters";
        e.ValidationResults.Add( validationResult );
        e.IsValid = false;
    }

    if ( order.Total < 0 )
    {
        GridViewCellValidationResult validationResult = new GridViewCellValidationResult();
        validationResult.PropertyName = "Total";
        validationResult.ErrorMessage = "Total must be positive";
        e.ValidationResults.Add( validationResult );
        e.IsValid = false;
    }
}
CopyVB.NET
Private Sub radGridView_RowValidating(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.GridViewRowValidatingEventArgs)
    Dim order As Order = TryCast(e.Row.DataContext, Order)
    If [String].IsNullOrEmpty(order.OrderNO) OrElse order.OrderNO.Length < 5 Then
        Dim validationResult As New GridViewCellValidationResult()
        validationResult.PropertyName = "OrderNO"
        validationResult.ErrorMessage = "OrderNO is required and must be at least five characters"
        e.ValidationResults.Add(validationResult)
        e.IsValid = False
    End If
    If order.Total < 0 Then
        Dim validationResult As New GridViewCellValidationResult()
        validationResult.PropertyName = "Total"
        validationResult.ErrorMessage = "Total must be positive"
        e.ValidationResults.Add(validationResult)
        e.IsValid = False
    End If
End Sub

Two things worth mentioning here:

  • In order to access the new values, you should grab the row's DataContext (in this case it is an Order). For the old values, use the OldValues property.
  • The GridViewCellValidationResult object is used for displaying error messages when the user enters wrong data.

The result from a failed validation can be seen on the next figure.

Once you have added such errors, you will have to explicitly clear them when needed. Please check this help article on how to clear user defined errors.

Tip

You can check this troubleshooting article on how to clear user defined errors.

Validating Data Through Data Annotations

With the Silverlight platform you can take advantage of the System.ComponentModel.DataAnnotations assembly. The following code snippet demonstrates how to use data annotation attributes to validate a property value (again within the property setter). It is even better when you use RIA services, since this code will be automatically added for you by the RIA Service's code generator.

The code snippet below shows you how to use DataAnnotations in order to validate the OrderNO property of the Order object.

CopyC#
[Required]
public string OrderNO
{
    get
    {
        return this.orderNo;
    }
    set
    {
        ValidationContext validationContext = new ValidationContext( this, null, null );
        validationContext.MemberName = "OrderNO";
        Validator.ValidateProperty( value, validationContext );
        this.orderNo = value;
    }
}
CopyVB.NET
<Required()> _
Public Property OrderNO() As String
    Get
        Return Me.orderNo
    End Get
    Set(ByVal value As String)
        Dim validationContext As New ValidationContext(Me, Nothing, Nothing)
        validationContext.MemberName = "OrderNO"
        Validator.ValidateProperty(value, validationContext)
        Me.orderNo = value
    End Set
End Property
Note

In order to use DataAnnotations you should add a reference to the System.ComponentModel.DataAnnotations assembly.

Tip

The following Validation Attributes are available for usage:

  • RequiredAttribute - specifies that a value must be provided for a property.
  • RegularExpressionAttribute - designates a regular expression to be used for validation of the associated member.
  • StringLengthAttribute - specifies the maximum and minimum number of characters that are allowed for an entity member.
  • RangeAttribute - designates the minimum and maximum constraints for the associated member.
  • DateTypeAttribute - specifies the name of an additional type to associate with an entity member.
  • CustomValidationAttribute - designates a customized method to execute to validate the entity member.

The result can be seen on the next figure.

radgridview managing data validation 050

Tip
Once the UI and Data validation passed (i.e. the Binding tried to update the value for the bound property), the CellValidated event is raised. The ValidationResult can be valid or not. Here you can also add a custom logic like changing the visual state of the editor (through the e.EditorElement).

See Also