How to: Validate data with SL/WPF RadGridView Part I validating on property/cell level via Data Annotations

Posted by: the telerik blogs, on 29 Oct 2009 | View original | Bookmarked: 0 time(s)

With the next Q3 2009 official release we are introducing a significant improvement to the validation mechanism of the RadGridView control. If we compare the new validation to the previous versions we add another validation layer (Data Layer) and refactoring of the related events. In a series of blog posts Ill try to clarify this mechanism with several small examples. Ill start the series with validation for a single cell.

 

How to: Validate data on a cell (property) level with RadGridView for Silverlight and WPF

 

The cell validation occurs when a GridViewCell is edited and its new data is about to be committed. At this moment CellValidating event is raised and since the new value is not yet committed to the underlying data object, here is the perfect place for applying a custom UI validation. By UI validation I mean the validation that occurs within the RadGridView control, which can be more restrictive than data validation according to specific business rules. Below is a code snippet that validates property FirstName of the Person object to be longer than 3 characters:

 

   1: ...
   2: this.radGridView.CellValidating += this.radGridView_CellValidating;
   3: }
   4:  
   5: private void radGridView_CellValidating(object sender, GridViewCellValidatingEventArgs e)
   6: {
   7: if (e.Cell.Column.UniqueName == "FirstName")
   8:     {
   9: if (e.NewValue.ToString().Length < 3)
  10:         {
  11:             e.IsValid = false;
  12:             e.ErrorMessage = "FirstName should be longer than 3 characters.";
  13:         }
  14:     }
  15: }

CellError

 

Note: For the sake of convenience all events involved into validation are exposed to the RadGridView control.

 

When you set e.IsValid = false, in the Validating events this will cancel the editing process and will return focus to the invalid GridViewCell. After this UI layer validation is successful (e.IsValid = true, which is the default value), Data layer validation occurs. This is the validation which is built in the business object implementation. There are several ways to do that:

 

  1. Throw exception when incorrect value is about to be set. This results into a binding validation error and GridViewBoundColumnBase editor enters into invalid state.
   1: public string FirstName
   2: {
   3:     get
   4:     {
   5: return this.firstName;
   6:     }
   7:     set
   8:     {
   9: if (value.Length < 3)
  10:         {
  11: throw new Exception("FirstName should be longer than 3 characters.");
  12:         }
  13: this.firstName = value;
  14:     }
  15: }

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

 

(Silverlight only)

2.    With the Silverlight platform you can take advantage from 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 Services code generator.

 

   1: [Required]
   2: public string LastName
   3: {
   4:     get
   5:     {
   6: return this.lastName;
   7:     }
   8:     set
   9:     {
  10:         Validator.ValidateProperty(value, new ValidationContext(this, null, null)
  11:         {
  12:             MemberName = "LastName"
  13:         });
  14: this.lastName = value;
  15:     }
  16: }

 

CellDataError 

 

Important: At this layer when data is validated and no error has occurred, the new data is committed to the data object.

 

After UI and Data layer validation are finished the CellValidated event occurs and here you can add custom actions. For example to change the visual state of the editor to invalid (when custom editor is used and it has no default invalid state associated with binding errors). The example shows how to change the editor background:

 

   1: private void radGridView_CellValidated(object sender, GridViewCellValidatedEventArgs e)
   2: {
   3:     ((Control) e.EditorElement).Background = new SolidColorBrush(Colors.Yellow);
   4: }

 

CellValidatedError 

 

You can play with this sample application in this blog post.Here it is.

 

Get Microsoft Silverlight

 

Here is the complete source code of the example.

 

Next time we will discuss row/object level validation. Stay tuned.


Happy validating!
Enjoy!

Advertisement
Free Agile Project Management Tool from Telerik
TeamPulse Community Edition helps your team effectively capture requirements, manage project plans, assign and track work, and most importantly, be continually connected with each other.
Category: Silverlight | Other Posts: View all posts by this blogger | Report as irrelevant | View bloggers stats | Views: 2104 | Hits: 11

Similar Posts

  • Validation - Part 3 - Server-Side more
  • Convert Web.UI Grid into a data entry spreadsheet more
  • Mapping with Expressions more
  • DataSet.WriteXmlSchema and DataSet.ReadXmlSchema Issue more
  • DataBinding with user control as a template more
  • Sharepoint 2007 WebParts Communication more
  • Quick Reference for the Atlas DataTable more
  • VB6 Migration pains - captured as a conversation more
  • DVXP's TEdit.NET Control more
  • An ASP.NET Custom Control for Dynamically Filtering Data - DataSetFilter more

News Categories

.NET | Agile | Ajax | Architecture | ASP.NET | BizTalk | C# | Certification | Data | DataGrid | DataSet | Debugger | DotNetNuke | Events | GridView | IIS | Indigo | JavaScript | Mobile | Mono | Patterns and Practices | Performance | Podcast | Refactor | Regex | Security | Sharepoint | Silverlight | Smart Client Applications | Software | SQL | VB.NET | Visual Studio | W3 | WCF | WinFx | WPF | WSE | XAML | XLinq | XML | XSD