int validation fails on empty TextBox

1.6k Views Asked by At

I've a TextBox bound to an int property with [Required] and [Range(1, 5)]attribute, when app starts TextBox gets 0, if I press Backspace and delete that 0, I get this message in Debug log:

System.Windows.Data Error: 7 : ConvertBack cannot convert value '' (type 'String'). BindingExpression:Path=Order.PartyCode; DataItem='OrderVM' (HashCode=66572856); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') FormatException:'System.FormatException: Input string was not in a correct format.
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at System.String.System.IConvertible.ToInt32(IFormatProvider provider)
   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
   at MS.Internal.Data.SystemConvertConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
   at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'

and validation doesn't work. I get same error if I use Nullable<int> instead of int!

Is it a must to have string properties to work with TextBox or there's way to solve this problem?

2

There are 2 best solutions below

1
Keith Stein On

You can fix this by using TargetNullValue in your binding, like so:
<TextBox Text="{Binding Test, TargetNullValue=''}"/>

This sets TargetNullValue to an empty string, which tells the binding that an empty string should be converted to null for the binding source.

If you're using a normal int, the result is that your property will not get set at all when the text is changed to an empty string. If you're using int? then your property will be set to null when the text changes to an empty string.

2
dotNET On

While Keith's answer will probably solve the problem at hand, the fact that user could type anything in a textbox, still poses a validation issue. A string type variable is much safer for TextBox.Text binding.

If you want to bind with an int property, there are other controls that might be more appropriate. Since your validation rule only allows int values between 1 and 5, a Slider, a ComboBox or even a set of RadioButtons would be a better approach.

If you're bent on using a TextBox, handle KeyDown event to prevent user from entering non-numeric keys.