Search code examples
c#winformsvalidationmvp

User Input Validation in Windows Forms Implementing Model View Presenter


I am trying to validate User Input in Windows Forms Application (using MVP design Pattern). Since this is my first project using MVP, I am not very clear where and how to put the user input validation code. To be specific, I have a Products form which contains two text box controls, Namely ProductName and ProductPrice.

Below is the code for my ProductForm, IProductView and ProductPresenter

IProductView.cs

 public interface IProductView
    {
        string ProductName { get; set; }
        int ProductPrice { get; set; }

        event EventHandler<EventArgs> Save; 
    }

frmProduct.cs

public partial class frmProduct : Form,IProductView
    {
        ProductPresenter pPresenter;

        public frmProduct()
        {
            InitializeComponent();
            pPresenter = new ProductPresenter(this);
        }

        public new string ProductName
        {
            get
            {
                return txtName.Text;
            }
        }

        public int ProductPrice
        {
            get
            {
                return Convert.ToInt32(txtPrice.Text);
            }
        }

        public event EventHandler<EventArgs> Save;
    }

ProductPresenter.cs

public class ProductPresenter
{
    private IProductView pView;

    public ProductPresenter(IProductView View)
    {
        this.pView = View;
        this.Initialize();
    }

    private void Initialize()
    {
        this.pView.Save += new EventHandler<EventArgs>(pView_Save);

    void pView_Save(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }
}

I do want to use the ErrorProvider(EP) Control + since I would be using EP control on many forms, I would really love if I could reuse most of the code by putting the EP code in some method and passing it the controls and appropriate message. Where should I put this validation code?

Regards,


Solution

  • I've used a base form with the error provider on and then had other forms inherit from this. I also put the visual error code in this base form also. This meant the same code is re-used. For Mvp, you could do something similar with a base form and an interface your application views inherit from. Your presenters would then see a uniform interface for setting validation states, messages, etc.