FORM C#: HOW TO NOT LEAVE TEXT BOX FIELD WITH DOUBLE VARIABLE VALUE IN BRACO

Asked

Viewed 57 times

-3

**Good afternoon, I’m running a basic program to improve programming but I’m having an error here, I’ve tried several ways and I can’t. It is a IMC calculation program in Windows Form, but when the program runs the Height and Weight field appears and when the user went to enter the data did not want the two fields to be blank because it seems to me that the cannot do pq the value is double and only has to check string because it is textbox, when I press the button to calculate with empty fields it closes at the height = Convert.todouble(txtaltura.text);. The beginning of the cogido is like this: Can someone help me? Double Height, Weight, BMI;

        Altura = Convert.ToDouble(txtAltura.Text);
        Peso = Convert.ToDouble(txtPeso.Text);
        if (txtAltura == null && txtPeso == null)
        {
            MessageBox.Show("DIGITE UM VALOR");

        }
        else
        {
            Altura = Convert.ToDouble(txtAltura.Text);
            Peso = Convert.ToDouble(txtPeso.Text);
            imc = Peso / (Altura * Altura);**
  • 1

    please uppercase letters on the internet means it’s screaming, please, "down-the-tone-of-voice" on the title!

  • Okay, it’s bad because I’m new here on the site and don’t deduce it. Thanks!

1 answer

4

There are several logic problems in your algorithm.

  1. You are trying to convert the values even before validating them.
  2. You are converting the values of the fields in a way that is not safe.
  3. Is repeating operations, converting values again.

What I suggest to you.

Use the function string.IsNullOrEmpty to validate whether or not your field has value. Example:

if (!string.IsNullOrEmpty(txtAltura.Text))
{
   //Algum código aqui
}

Use the function double.TryParse to try parsing the field value for a type value double. Example:

double.TryParse(txtAltura.Text, out double altura)

Finally, I leave here how this implementation should be done in my vision:

//Aqui valida se os campos tem valor
if (string.IsNullOrEmpty(txtAltura.Text) || string.IsNullOrEmpty(txtPeso.Text))
{
    MessageBox.Show("DIGITE UM VALOR");
}
else
{
    //Aqui tenta fazer parse do valor do campo altura
    if (!double.TryParse(txtAltura.Text, out double altura))
    {
        MessageBox.Show("ALTURA INVÁLIDA");
    }
    else
    {
        //Aqui tenta fazer parse do valor do campo altura
        if (!double.TryParse(txtPeso.Text, out double peso))
        {
            MessageBox.Show("PESO INVÁLIDO");
        }
        else
        {
            //Se deu tudo certo, calcula o imc
            var imc = peso / (altura * altura);
        }
    }
}
  • Thanks man, that’s right, I’m sorry it’s because I’m new in the area, so I had a lot of mistakes kkk how to say wrong that you learn right ? but thank you very much for your attention.

Browser other questions tagged

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