OXO
OXO

Reputation: 1088

Preventing Format Exception in Numeric Entry

In my .NET MAUI App I use an Entry in a View with the following setting:

<Entry Text="{Binding EntryInput}" Placeholder="{Binding PlaceholderString}" Keyboard="{Binding KeyboardSetting}" Margin="5, 0, 5, 15" x:Name="entryControl"/>

Depending on the type of input, I use KeyboardSetting Numeric or default. The BindableProperty is as follows:

public static readonly BindableProperty EntryInputProperty = BindableProperty.Create(nameof(EntryInput), typeof(string), typeof(MyInputView), default(string), BindingMode.TwoWay);
...
public string EntryInput
{
    get => (string)GetValue(EntryInputProperty);
    set => SetValue(EntryInputProperty, value);
}

When the View is loaded, I want to clear the Text of the Entry and set it to string.Empty (not to the default value "0" also for Numeric Entry). When I use KeyboardSetting "Numeric", I get a System.FormatException: 'The input string '' was not in a correct format.'

Can I prevent this in a way and still have the Entry really empty (not "0")? Also when a user deletes all the text from the Entry the exception is thrown.

In my case, I would say it also make the UI slow when the UI is loaded.

Are there solutions for that?

==== Stacktrace of the Exception ====

   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, ReadOnlySpan`1 value, TypeCode type)
   at System.Number.ParseDouble(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
   at System.Double.Parse(String s, IFormatProvider provider)
   at System.Convert.ToDouble(String value, IFormatProvider provider)
   at System.String.System.IConvertible.ToDouble(IFormatProvider provider)
   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
   at Microsoft.Maui.Controls.BindingExpression.TryConvert(Object& value, BindableProperty targetProperty, Type convertTo, Boolean toTarget) in D:\a\_work\1\s\src\Controls\src\Core\BindingExpression.cs:line 464

Upvotes: 1

Views: 997

Answers (1)

OXO
OXO

Reputation: 1088

As @Jianwei Sun - MSFT commented, I tried it with setting Entry.Text = null instead of setting it to string.Empty when I have a Numeric Entry. Great and thanks for this hint!

Upvotes: 0

Related Questions