简体   繁体   中英

User input validation with validation on properties

I have a Name Property in one class, that contains some validations:

public string Name
{
    get { return name; }

    set 
    {
        if (! RegEx.IsMatch(value, "\w{1-35}"))
           throw new Exception("Name must be 1-35 alfanum");
        this.name = value;
    }
}

When I bind this property to the "Text" property of a TextBox control in a WinForm application, the user inputted value will be validate with this rule, so how can I catch this exception and show it with an ErrorProvider object?

When adding binding to your control, subscribe to it's Parse event (occurs when the value of a data-bound control changes):

textBox1.DataBindings.Add("Text", person, "Name");
textBox1.DataBindings["Text"].Parse += Binding_Parse;

Then in event handler do following:

void Binding_Parse(object sender, ConvertEventArgs e)
{
    var binding = (Binding)sender;
    try
    {
        binding.Parse -= Binding_Parse; // remove this event handler
        binding.WriteValue(); // try write control's value to data source
        errorProvider1.SetError(binding.Control, "");
    }
    catch (Exception error)
    {
        errorProvider1.SetError(binding.Control, error.Message);
    }
    finally
    {
        binding.Parse += Binding_Parse; // subscribe back
    }
}

You need to remove and add handler, because you are writing control's value manually. That will cause writing value back from data source to control and raising this event again. So, to avoid stack overflow, you need this trick.

You can reuse same event handler for all data bindings you have:

foreach (Control control in Controls)
    foreach (Binding binding in control.DataBindings)
        binding.Parse += Binding_Parse;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM