Click here to Skip to main content
14,022,795 members
Click here to Skip to main content
Add your own
alternative version


20 bookmarked
Posted 23 Oct 2011
Licenced CPOL

Validation in WPF Toolkit’s DataGrid

, 5 Nov 2011
Rate this:
Please Sign up or sign in to vote.
Describe validation when presenting data in WPF Toolkit’s DataGrid.



This article presents a way to validate data, which is shown in the CodePlex WPF Toolkit’s DataGrid control ( The validation is done using the IDataError interface and works in .NET Framework 3.5 and above.


Recently, I had to validate data in a grid control. I didn’t want to buy a third party component, but decided to use the WPF Toolkit’s DataGrid.

After reading the excellent article from Colin Eberhardt (, I realized some problems when using .NET Framework 3.5 especially when data is not changed by the user but added programmatically.

I had to implement a small tool which could be deployed through extracting a Zip file. Because of this, I didn’t want the user to need to install .NET Framework 4.0 only to solve my validation problems.

In the end, I did the data validation as described below which works with .NET Framework 3.5.

Using the Code

The application uses the MVVM pattern. If you haven’t heard about it, I recommend you read the good articles from Josh Smith (

The class where the validation takes place is called <PersonVM>. This class contains the following properties:

  • String FirstName
  • String LastName
  • Boolean HasJob (Indicates if the person has a job or is out-of-work)
  • String JobName

Two things should be validated:

  1. The first name and last name should only contain A-Za-z chars and spaces.
  2. It should not be allowed for a person to have the HasJob flag set, but the JobName empty, or vice versa.

The first rule can be checked by validating each name property. To check the second rule, it is not only sufficient to validate a single property, but multiple properties. This validation takes place on the whole Person object.

The validation is implemented in the following PersonVM indexer (desired by the <IDataError> interface):

public string this[string columnName]
    // apply property level validation rules
    if (columnName == "FirstName")
      if (String.IsNullOrEmpty(this.FirstName))
        return "First Name needs to be filled";
      if (!MyNameEx.Match(this.FirstName).Success)
        return "First Name may only contain characters or spaces";
    if (columnName == "LastName")
      if (String.IsNullOrEmpty(this.LastName))
        return "Last Name needs to be filled";
      if (!MyNameEx.Match(this.LastName).Success)
        return "Last Name may only contain characters or spaces";
    // Method ValidateJob applies object level validation. In this example the consistency 
    // of the properties HasJob and JobName is checked on object level. An error is 
    // announced for JobName only. Otherwise the red error border would be presented for 
    // the JobName and the HasJob field and the error correction would be inconvenient 
    // for the user - try it out by uncommenting following line
    // if (columnName == "JobName" || columnName == "HasJob")
    if (columnName == "JobName")
      return ValidateJob();
    return "";

private string ValidateJob()
  if (!this.HasJob && !String.IsNullOrEmpty(this.JobName))
    return "Job Name is given, but Job Flag is not set!";
  if (this.HasJob && String.IsNullOrEmpty(this.JobName))
    return "Job Name is not given, but Job Flag is set!";
  return "";

The second method of the IDataError is not written individually for PersonVM and can be put into a base or helper class.

public string Error
    StringBuilder error = new StringBuilder();
    // iterate over all of the properties
    // of this object - aggregating any validation errors
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(this);
    foreach (PropertyDescriptor prop in props)
      String propertyError = this[prop.Name];
      if (propertyError != string.Empty)
        error.Append((error.Length != 0 ? ", " : "") + propertyError);
    return error.Length == 0 ? null : error.ToString();

The validation of multiple fields needs to be announced by one field - JobName in my example - because the user cannot edit multiple fields in one step to correct a multiple field error. For this reason, it is necessary to simulate that JobName has been changed when the HasJob checkbox is updated. This notification is done in the HasJob setter:

public Boolean HasJob
    return myHasJob;
    myHasJob = value;

The corresponding XAML code of the DataGrid is displayed below:

<Window x:Class="ValidationInWpfDatagrid.View.MainWindow" 




        Title="MainWindow" Height="350" Width="525">
      <RowDefinition Height="20"/>
    <dg:DataGrid  Name="myDataGrid" AutoGenerateColumns="False" 

    ItemsSource="{Binding PersonList}" CanUserAddRows="True">
        <Style TargetType="{x:Type dg:DataGridCell}">
          <Setter Property="TextBlock.ToolTip" 

                    Value="{Binding Error}" />
        <dg:DataGridTextColumn Header="FirstName" 

           Binding="{Binding Path=FirstName, ValidatesOnDataErrors=True}" 

           Width="*" />
        <dg:DataGridTextColumn Header="LastName" 

           Binding="{Binding Path=LastName, ValidatesOnDataErrors=True}" 

           Width="*" />
        <dg:DataGridCheckBoxColumn Header="Job Flag" 

           Binding="{Binding Path=HasJob, ValidatesOnDataErrors=True}" 

           Width="*" />
        <dg:DataGridTextColumn Header="Job's Name" 

           Binding="{Binding Path=JobName, ValidatesOnDataErrors=True}" 

           Width="*" />
    <Button Grid.Row="1" Name="myBtnAddPerson" 

       Content="Add Person" Command="{Binding AddPersonCommand}" />

Have fun!


  • 23 Oct 2011: First revision.
  • 5 Nov 2011: Corrected object level validation.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Frank Augustin
Germany Germany
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy Vote 5 Pin
Shemeemsha (ഷെമീംഷ)2-Oct-14 19:36
memberShemeemsha (ഷെമീംഷ)2-Oct-14 19:36 
QuestionHow can we do this for a DataGridTemplateColumn? Pin
XiaoAnn19-Dec-12 6:49
memberXiaoAnn19-Dec-12 6:49 
Questionvery nice Pin
BillW337-Nov-11 9:20
professionalBillW337-Nov-11 9:20 
QuestionWhen in error, the text field is not editable. Pin
Member 65991223-Oct-11 6:14
memberMember 65991223-Oct-11 6:14 
AnswerRe: When in error, the text field is not editable. Pin
Frank Augustin23-Oct-11 20:37
memberFrank Augustin23-Oct-11 20:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190417.4 | Last Updated 5 Nov 2011
Article Copyright 2011 by Frank Augustin
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid