简体   繁体   English

用户输入验证和属性验证

[英]User input validation with validation on properties

I have a Name Property in one class, that contains some validations: 我在一个类中有一个Name属性,其中包含一些验证:

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? 当我将此属性绑定到WinForm应用程序中TextBox控件的"Text"属性时,将使用此规则验证用户输入的值,那么如何捕获此异常并通过ErrorProvider对象显示它?

When adding binding to your control, subscribe to it's Parse event (occurs when the value of a data-bound control changes): 向控件添加绑定时,请订阅它的Parse事件(在数据绑定控件的值更改时发生):

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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