简体   繁体   中英

C# Override OnValidating to support null value but breaks Data Binding

I have a CustomTextBox which inherits from TextBox and overwrites the OnValidating method to allow empty strings. CustomTextBox is bound to Property Price in Domain.

public class CustomTextBox
{
    protected override void OnValidating(...)
    {  
       if(Text=="") 
       {
           Text = null;
           return;
       }
       base.OnValidating(e);
    }
}
public class Domain
{
    public System.Nullable<decimale> Price
    { ... }
}

All works well except that this prevents users froming setting Price to null. Text=null; did not propogate to the domain object. Is there a way to reset Price back to null when user clears out the TextBox?

If you are using Binding to propagate values to the domain object, then you should put this logic in the Parse event instead.

// Add binding
var b = new Binding("Text", myDataSource, "BoundProperty");
b.Parse += OnNullableTextBindingParsed;
myTextBox.DataBindings.Add(b);


// Sample parse handler
private void OnNullableTextBindingParsed(object sender, ConverterEventArgs e)
{
    if (e.Value == String.Empty) e.Value = null;
}

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