18

I recently used ASP.Net MVC with DataAnnotations and was thinking of using the same approach for a Forms project but I'm not sure how to go about it.

I have set my attributes but they do not seem to get checked when I click Save.

UPDATE: I have used Steve Sanderson's approach which will check for attributes on my class and return a collection of errors like so:

        try
        {
            Business b = new Business();
            b.Name = "feds";
            b.Description = "DFdsS";
            b.CategoryID = 1;
            b.CountryID = 2;
            b.EMail = "SSDF";
            var errors = DataAnnotationsValidationRunner.GetErrors(b);
            if (errors.Any())
                throw new RulesException(errors);

            b.Save();
        }
        catch(Exception ex)
        {

        }

What do you think of this approach?

1
  • Take a look at DataAnnotations Attributes in Windows Forms: - Visibility of columns: by [Browsable] attribute. You can also rely on AutoGenerateField property of the [Display] attribute. - Header text of columns: by Name of the [Display] attribute. - Order of columns: by Order of the [Display] attribute. - Format of columns: by [DisplayFormat] attribute. - Tooltip of columns: by Description of the [Display] attribute. - Type of columns: by [UIHint] attribute. Commented Dec 2 at 18:31

4 Answers 4

27

Here's a simple example. suppose you have an object like the following

using System.ComponentModel.DataAnnotations;

public class Contact
{
    [Required(AllowEmptyStrings = false, ErrorMessage = "First name is required")]
    [StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]
    public string FirstName { get; set; }

    public string LastName { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime Birthday { get; set; }
}

And suppose we have a method that creates an instance of this class and tries to validate its properties, as listed below

    private void DoSomething()
    {
        Contact contact = new Contact { FirstName = "Armin", LastName = "Zia", Birthday = new DateTime(1988, 04, 20) };

        ValidationContext context = new ValidationContext(contact, null, null);
        IList<ValidationResult> errors = new List<ValidationResult>();

        if (!Validator.TryValidateObject(contact, context, errors,true))
        {
            foreach (ValidationResult result in errors)
                MessageBox.Show(result.ErrorMessage);
        }
        else
            MessageBox.Show("Validated");
    }

The DataAnnotations namespace is not tied to the MVC framework so you can use it in different types of applications. the code snippet above returns true, try to update the property values to get validation errors.

And make sure to checkout the reference on MSDN: DataAnnotations Namespace

Sign up to request clarification or add additional context in comments.

1 Comment

You rock!.. This is the real answer of the question!.. Thanks a lot...
5

Steve's example is a bit dated (though still good). The DataAnnotationsValidationRunner that he has can be replaced by the System.ComponentModel.DataAnnotations.Validator class now, it has static methods for validating properties and objects which have been decorated with DataAnnotations attributes.

2 Comments

There's not a ton of examples of using this Validator class outside of MVC, so you probably want to call it using something like this: var results = new List<ValidationResult>(); var success = Validator.TryValidateObject(thing, new ValidationContext(thing, null, null), results);
Also note that if you're using [Range] you'll have to add true after results in the TryValidateObject method.
2

I found a decent example of using DataAnnotations with WinForms using the Validator class, including tying into the IDataErrorInfo interface so ErrorProvider can display the results.

Here is the link. DataAnnotations Validation Attributes in Windows Forms

Comments

-1

If you use newest versions of Entity Framework you can use this cmd to get a list of your errors if existing:

YourDbContext.Entity(YourEntity).GetValidationResult();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.