Skip to main content Skip to footer

Validation using IDataErroInfo in WPF C1DataGrid

IDataErrorInfo interface provides the ability to validate data and necessary error information that a user interface can bind to. Lets see how we can use the IDataErrorInfo and validate data in C1DataGrid. C1DataGrid has immense flexibility that allows us to add errors manually to the rows. That's pretty useful in scenarios when binding to simple collections (with no error information) and binding to native datatable. Below is a simple class implementing the IDataErrorInfo:

public class Person : IDataErrorInfo  
 {  
    private int age;  
    private string name;  

    public int Age  
    {  
       get { return age; }  
       set { age = value; }  
    }  
    public string Name  
    {  
       get { return name; }  
       set { name = value; }  
    }  
    public string Error  
    {  
       get  
       {  
          return null;  
       }  
    }  
    public string this[string name]  
    {  
       get  
       {  
          string result = null;  
          if (name == "Age")  
          {  
             if (this.age < 20 || this.age > 50)  
             {  
                   result = "Age must be less than 50 and greater than 20";  
             }  
          }  
          if (name == "Name")  
          {  
             if (this.name.Length < 3)  
                result = "Too Small Name";  
          }  
          return result;  
       }  
    }  
 }

The important trick here is to set the ValidatesOnDataErrors property on the column binding object to true. Below is the C1DataGrid definition in XAML with manual columns:

<c1:C1DataGrid  x:Name="c1DataGrid1" AutoGenerateColumns="False">  
 <c1:C1DataGrid.Columns>  
 <c1:DataGridTextColumn Header="Name" Binding="{Binding Name,Mode=TwoWay,ValidatesOnDataErrors=True}"/>  
 <c1:DataGridNumericColumn Header="Age" Binding="{Binding Age,Mode=TwoWay,ValidatesOnDataErrors=True}"/>  
 </c1:C1DataGrid.Columns>  
 </c1:C1DataGrid>

We will validate the data on the 'CommittingEdit' event of the C1DataGrid and manually add the validation results to the row:

c1DataGrid1.CommittingEdit += (s, e) =>  
 {  
    if (Validation.GetHasError(e.EditingElement))  
    {  
       var ve = Validation.GetErrors(e.EditingElement);  
       e.Row.ValidationResults.Add(new System.ComponentModel.DataAnnotations.ValidationResult((ve[0]).ErrorContent.ToString(), new string[] { e.Column.Name }));  
    }  
    else  
    {  
       foreach (var result in e.Row.ValidationResults)  
       {  
          if (result.MemberNames.First() == e.Column.Name)  
          {  
             e.Row.ValidationResults.Remove(result);  
             break;  
          }  
       }  
    }  
 };

Please refer to the attached sample for the complete implementation. Download Sample

MESCIUS inc.

comments powered by Disqus