Leonhard Keßler
Leonhard Keßler

Reputation: 45

Nulling an Entry results in crash, TextChanged

I have an entry that collects a number that is used afterward as a double. It works all fine until one deletes all numbers in the entry to enter a new one.

I tried fixing it by throwing a new Exception as soon as the Text is null but it still crashes with

Input string was not in a correct format. (FormatException)

the error occurs in moneyOutput.Text = Convert.ToDouble(moneyInput.Text).ToString() + "€";

here is my xaml code:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Bierrechner.Priceentry"
         BackgroundColor="#8c1029"
         Title="Eingabe">
<ScrollView>
    <StackLayout Margin="0,30,0,0" >


        <Entry x:Name="moneyInput"  TextChanged="MoneyInput_TextChanged" Placeholder="z.B. 34,99" PlaceholderColor="Gray" TextColor="White" Keyboard="Numeric"/>
        <Label x:Name="moneyOutput" Margin="0,40,0,0" HorizontalTextAlignment="Center" FontSize="Large" TextColor="Orange"/>
        <Button Text="Weiter" Clicked="Button_Clicked" HorizontalOptions="Center" VerticalOptions="EndAndExpand"/>


    </StackLayout>
</ScrollView>

and my xaml.cs code:

private void MoneyInput_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (moneyInput.Text != null)
        {
            moneyOutput.Text = Convert.ToDouble(moneyInput.Text).ToString() + "€";
            sharePrice = Convert.ToDouble(moneyInput.Text);
        }

        else if (moneyInput.Text == null) 
        {
            throw new ArgumentException("String cannot be null or empty");                
        }
    }

I noticed that the if (moneyInput.Text != null) doesn't have any effect because the code is still executed.

Upvotes: 0

Views: 686

Answers (1)

kennyzx
kennyzx

Reputation: 12993

Your code just check again null.

if (moneyInput.Text != null)

You need to also check against empty string.

if (!string.IsNullOrEmpty(moneyInput.Text))

Actually the Text property won’t be null when the input box is cleared, it is just an empty string.

Also consider using Double.TryParse, instead of Convert.ToDouble. TryParse method won’t throw an exception no matter what the value of the string is, if the string is null, empty, or simply ill-formed, the method just returns false.

Upvotes: 1

Related Questions