Using DataAnnotations on Windows Forms project

元气小坏坏 提交于 2019-11-30 00:21:14

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.

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

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

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!