none
Data annotations com windows forms? RRS feed

  • Pergunta

  • No asp.net e no mvc existe o data annotations para validação do modelo, existe essa mesma possibilidade no windows forms com c#?
    sexta-feira, 26 de outubro de 2012 17:38

Respostas

  • Sim Thiago.

    Com  o link que postei da para fazer no Windows Forms. Basta adicionar no seu projeto uma referencia da DLL System.ComponentModel.DataAnnotations, veja este código:

    using System;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    
    namespace WindowsFormsApplication2
    {
        [Serializable]
        public class EntityValidationResult
        {
            public IList<ValidationResult> ValidationErrors { get; private set; }
            public bool HasError
            {
                get { return ValidationErrors.Count > 0; }
            }
    
            public EntityValidationResult(IList<ValidationResult> violations = null)
            {
                ValidationErrors = violations ?? new List<ValidationResult>();
            }
        }
    
        public class DataAnnotation
        {
            public static EntityValidationResult ValidateEntity<T>(T entity)
            {
                return new EntityValidator<T>().Validate(entity);
            }
        }
    
        public class EntityValidator<T>
        {
            public EntityValidationResult Validate(T entity)
            {
                var validationResults = new List<ValidationResult>();
                var vc = new ValidationContext(entity, null, null);
                var isValid = Validator.TryValidateObject(entity, vc, validationResults, true);
    
                return new EntityValidationResult(validationResults);
            }
        }
    
        public class Teste
        {
            [Required(AllowEmptyStrings = false, ErrorMessage = "Name is Required Field.")]
            public string Name { get; set; }
            [StringLength(20, MinimumLength = 4, ErrorMessage = "Address Length Between 4 to 20 character")]
            public string AddressLine { get; set; }
            [RegularExpression(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$", ErrorMessage = "Email Address is not Valid.")]
            public string EmailAddress { get; set; }
            [Range(1, 90)]
            public int Age { get; set; }
        }
    
    
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                Teste t = new Teste();
    
                t.EmailAddress = "x";
    
                var resultados = DataAnnotation.ValidateEntity<Teste>(t);
    
                if (resultados.HasError)
                {
                    foreach (var erro in resultados.ValidationErrors)
                    {
                        MessageBox.Show("Erro: " + erro.ErrorMessage);
                    }
    
                }
            }
        }
    }


    Vitor Mendes | Seu feedback é muito importante para todos!
    Visite o meu site: http://www.vitormendes.com.br/

    sexta-feira, 26 de outubro de 2012 18:13

Todas as Respostas

  • Thiago, acho que se usa da mesma estrutura de validação, porem é necessário criar um método auxiliar para validar seu objeto, veja este tutorial:

    http://www.c-sharpcorner.com/UploadFile/ff2f08/validation-using-data-annotation-to-custom-model-or-class/


    Vitor Mendes | Seu feedback é muito importante para todos!
    Visite o meu site: http://www.vitormendes.com.br/

    sexta-feira, 26 de outubro de 2012 17:46
  • Uso desta forma no mvc com data annotations, quero usar dessa forma no windows forms.

    [Required(AllowEmptyStrings = false, ErrorMessage = "Name is Required Field.")]
        public string Name { get; set; }
        [StringLength(20, MinimumLength = 4, ErrorMessage = "Address Length Between 4 to 20 character")]
        public string AddressLine1 { get; set; }
        [RegularExpression(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$", ErrorMessage = "Email Address is not Valid.")]
        public string EmailAddress { get; set; }
        [Range(1, 90)]
        public int Age { get; set; }
    sexta-feira, 26 de outubro de 2012 17:58
  • Sim Thiago.

    Com  o link que postei da para fazer no Windows Forms. Basta adicionar no seu projeto uma referencia da DLL System.ComponentModel.DataAnnotations, veja este código:

    using System;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    
    namespace WindowsFormsApplication2
    {
        [Serializable]
        public class EntityValidationResult
        {
            public IList<ValidationResult> ValidationErrors { get; private set; }
            public bool HasError
            {
                get { return ValidationErrors.Count > 0; }
            }
    
            public EntityValidationResult(IList<ValidationResult> violations = null)
            {
                ValidationErrors = violations ?? new List<ValidationResult>();
            }
        }
    
        public class DataAnnotation
        {
            public static EntityValidationResult ValidateEntity<T>(T entity)
            {
                return new EntityValidator<T>().Validate(entity);
            }
        }
    
        public class EntityValidator<T>
        {
            public EntityValidationResult Validate(T entity)
            {
                var validationResults = new List<ValidationResult>();
                var vc = new ValidationContext(entity, null, null);
                var isValid = Validator.TryValidateObject(entity, vc, validationResults, true);
    
                return new EntityValidationResult(validationResults);
            }
        }
    
        public class Teste
        {
            [Required(AllowEmptyStrings = false, ErrorMessage = "Name is Required Field.")]
            public string Name { get; set; }
            [StringLength(20, MinimumLength = 4, ErrorMessage = "Address Length Between 4 to 20 character")]
            public string AddressLine { get; set; }
            [RegularExpression(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$", ErrorMessage = "Email Address is not Valid.")]
            public string EmailAddress { get; set; }
            [Range(1, 90)]
            public int Age { get; set; }
        }
    
    
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                Teste t = new Teste();
    
                t.EmailAddress = "x";
    
                var resultados = DataAnnotation.ValidateEntity<Teste>(t);
    
                if (resultados.HasError)
                {
                    foreach (var erro in resultados.ValidationErrors)
                    {
                        MessageBox.Show("Erro: " + erro.ErrorMessage);
                    }
    
                }
            }
        }
    }


    Vitor Mendes | Seu feedback é muito importante para todos!
    Visite o meu site: http://www.vitormendes.com.br/

    sexta-feira, 26 de outubro de 2012 18:13