views:

1039

answers:

1

I like the Validation Application Block from the Enterprise Library :-)
Now i would like to use the DataAnnotations in Winforms, as we use asp.net Dynamic Data as well. So that we have common technologies over the whole company.
And also the Data Annotations should be easier to use.

How can I do something similiar in Winforms like Stephen Walter did within asp.net MVC?

+5  A: 

I adapted a solution found at http://blog.codeville.net/category/validation/page/2/

public class DataValidator
    {
    public class ErrorInfo
    {
        public ErrorInfo(string property, string message)
        {
            this.Property = property;
            this.Message = message;
        }

        public string Message;
        public string Property;
    }

    public static IEnumerable<ErrorInfo> Validate(object instance)
    {
        return from prop in instance.GetType().GetProperties()
               from attribute in prop.GetCustomAttributes(typeof(ValidationAttribute), true).OfType<ValidationAttribute>()
               where !attribute.IsValid(prop.GetValue(instance, null))
               select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty));
    }
}

This would allow you to use the following code to validate any object using the following syntax:

var errors = DataValidator.Validate(obj);

if (errors.Any()) throw new ValidationException();
Matt Murrell
I like that.Have to try it, but it looks like it does the job... The manual call to Validate() is not so nice, but we could avoid this, by implementing that in our UserControls
Peter Gfader