How to treat an empty entry?

Asked

Viewed 144 times

1

I have 4 text entries 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 code Behind I convert them to double, make a calculation and send the result to a Page2 through Classe2


 //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 is not filled in, the following error occurs:

I’ve tried solutions like:


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

        class2 = new Class2();

        double a, 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));
        }
    }
  • Instead of a = Double.Parse(Area.Text); try to use Double.TryParse(Area.Text, a);

  • I tried, appears "Argument 2 should not be transmitted with the keyword 'out'". I do not know where the error is, nor how to solve it.

  • Sorry, I forgot a little something, the right thing is Double.TryParse(Area.Text, out var a);

2 answers

3


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

string.IsNullOrWhiteSpace(Densidade.Text)

Obviously you will for each of them. You can use the || even.

And do not make a data conversion without being sure that it is valid, for this use so:

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

Can use a || there too and have only one 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 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 put in the Github for future reference.

Enjoy and take out all these await and methods Async that they are only slowing down the application. Just go back to using them in place where you need them and after you understand how it works. It’s not making it faster, on the contrary, it’s slower that way. I have my doubts whether the message should be presented like this, and whether it should have this ok, maybe it’s another "mistake".

Something tells me that this Classe2 is not necessary, apart from the fact that the name does not mean anything. even if you use it, should have a better constructor. Her field name doesn’t make sense either.

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

  • @Diegorafaelsouza yes, of course, I had forgotten, thank you

-1

Try to use the 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 as well, if you need

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 point number equivalent double precision floating parameter S, if conversion was successful, or zero, if conversion failed.

If you want to understand better

Browser other questions tagged

You are not signed in. Login or sign up in order to post.