How to handle an empty Entry?

1

I have 4 text inputs and a button:

<Entry x:Name="Densidade"
           Keyboard="Numeric"/>

<Entry x:Name="Volume"
           Keyboard="Numeric"/>

<Entry x:Name="Area"
           Keyboard="Numeric"/>

<Entry x:Name="Custo"
           Keyboard="Numeric"/>

<Button x:Name="Button"
            Text="Calcular"
            HorizontalOptions="FillAndExpand"
            VerticalOptions="EndAndExpand"
            Clicked="Handle_Clicked"/>

In the Behind code I convert them to double, I make a calculation and send the result to a Page2 through Class2

 //Botão que transforma os dados em variáveis e passa para a página de resultados
    private async void Handle_Clicked(object sender, EventArgs e)
    {
        class2 = new Class2();

        //Converte os valores obtidos na entrada em tipo double
        double a, d, r, v;
        a = Double.Parse(Area.Text);
        d = Double.Parse(Densidade.Text);
        r = Double.Parse(Custo.Text);
        v = Double.Parse(Volume.Text);

        //calculo
        class2.Calculo1 = d * a * (v / 1000) * r;

        //chama Page1 passando objeto class2
        await Navigation.PushAsync(new Page1(class2));
    }

However, if any of the entries are not filled, the following error occurs:

I'vetriedsolutionslike:

privateasyncvoidHandle_Clicked(objectsender,EventArgse){class2=newClass2();doublea,d,r,v;if(Densidade.Text=="")
            d = 0;
        else
            d = Double.Parse(Densidade.Text);

        if (Volume.Text == "")
            v = 0; 
        else
            v = Double.Parse(Volume.Text);

        if (Area.Text == "")
            a = 0;
        else
            a = Double.Parse(Area.Text);

        if (Custo.Text == "")
            r = 0;
        else
            r = Double.Parse(Custo.Text);

        //calculo
        class2.Calculo1 = d * a * (v / 1000) * r;

        //chama Page1 passando objeto class2
        await Navigation.PushAsync(new Page1(class2));
    }

or

private async void Handle_Clicked(object sender, EventArgs e)
    {


        if ((Densidade.Text == "") || (Volume.Text == "")
            || (Area.Text == "") || (Custo.Text == ""))
        {
            await Navigation.PushAsync(new MainPage());
            await DisplayAlert("Atenção", @"Todos os campos devem ser preenchidos", "Ok");
        }
        else
        {
            class2 = new Class2();

            //Converte os valores obtidos na entrada em tipo double
            double a, d, r, v;
            a = Double.Parse(Area.Text);
            d = Double.Parse(Densidade.Text);
            r = Double.Parse(Custo.Text);
            v = Double.Parse(Volume.Text);

            //calculos
            class2.Calculo1 = d * a * (v / 1000) * r;

            //chama Page1 passando objeto class2
            await Navigation.PushAsync(new Page1(class2));
        }
    }
    
asked by anonymous 04.07.2018 / 16:03

2 answers

3

If you want to even insist on the message that the fields need to be filled then change the empty check to:

string.IsNullOrWhiteSpace(Densidade.Text)
Obviously will do for each of them. You can use || itself.

And do not do a data conversion without making sure it's valid, so use this:

if (!double.TryParse(Area.Text, out var a) DisplayAlert("Atenção", @"Valores digitados são inválidos", "Ok");

You can use a || there too and have only a if for the four data to be validated.

But of course you can omit the check if it is empty and only control if the value is valid, after all if it is empty it is invalid equal. I would do so:

if (!double.TryParse(Area.Text, out var area) || !double.TryParse(Densidade.Text, out var densidade) || !double.TryParse(Custo.Text, out var custo) || !double.TryParse(Volume.Text, out var volume)) {
        await Navigation.PushAsync(new MainPage()); //rever isto
        DisplayAlert("Atenção", @"Todos os campos devem ser preenchidos com valores válidos", "Ok");
    } else {
        var class2 = new Class2();
        class2.Calculo1 = densidade * area * (volume / 1000) * custo;
        await Navigation.PushAsync(new Page1(class2)); //rever isto
    }

I placed GitHub for future reference .

Take advantage of all these await and Async methods as they are only slowing down the application. Just go back to using them where you need them and then you understand how it works. It's not making it any faster, on the contrary, it's slower like that. I have my doubts if the message should be presented like this, and if it should have this ok , maybe it is another "error".

Something tells me that this Classe2 is not necessary, other than the fact that the name does not mean anything. even if you use it, you should have a better builder. The name of her field does not make sense either.

If cost is a monetary value it should be decimal and not double . One might wonder if the rest should too.

    
04.07.2018 / 16:25
-1

Try to use Double.TryParse(S, Result);

 //Botão que transforma os dados em variáveis e passa para a página de resultados
    private async void Handle_Clicked(object sender, EventArgs e)
    {
        class2 = new Class2();

        //Converte os valores obtidos na entrada em tipo double
        double a, d, r, v;
        Double.TryParse(Area.Text, out var a);
        Double.TryParse(Densidade.Text, out var d);
        Double.TryParse(Custo.Text, out var r);
        Double.TryParse(Volume.Text, out var v);

        //calculo
        class2.Calculo1 = d * a * (v / 1000) * r;

        //chama Page1 passando objeto class2
        await Navigation.PushAsync(new Page1(class2));
    }

You can use it as a condition too if you need to

if (Double.TryParse(Area.Text, out a))
  Console.WriteLine(number);
else
  Console.WriteLine("{0} Falha na conversão.", value);
  

When this method returns, it contains the equivalent of the point number   precision of the S parameter, if the conversion was   successful, or zero, if the conversion failed.

If you want to understand better

    
04.07.2018 / 16:24