How to make an internal calculation in Textbox?

Asked

Viewed 35 times

1

I need to calculate a value entered in Textbox and this value I enter is multiplied by 9,81. So all the numbers I insert in this Textbox will be multiplied by 9,81 and you will have to show me the result on the Textbox.

Example: I type in the Textbox: 6000 and that 6000 will be multiplied by 9.81. And the same textbox will have to show me 58.860.

Observing: the values I enter will be random, only the 9.81 shall be fixed in the calculation.

private void txtCalcular_TextChanged(object sender, EventArgs e) 
{
    Calcular = double.Parse((txtCalcular.Text).ToString());
    ResultadoCalcular = double.Parse(
         (txtCalcular.Text = (Calcular * 9.81).ToString())
    );
}

I tried to do it this way too, but without success:

Calcular = double.Parse((txtCalcular.Text = (Calcular * 9.81).ToString()));

1 answer

1


The first problem is that it is considering that the person will always type something right, which can not guarantee and will break the application, have to treat it.

With a valid data is just to make the account simple, convert it to text and store it in the field where you already had the value. Don’t have to go around repeating things. Mainly you can’t assign the value to the field in the middle of an operation that will do something else.

I answered what’s in the question.

private void txtCalcular_TextChanged(object sender, EventArgs e) {
    if (!double.TryParse(txtCalcular.Text, out var resultado)) {
        //faça alguma coisa aqui para indicar que houve erro de digitação;
        return;
    }
    txtCalcular.Text = (resultado * 9.81).ToString());
}

I put in the Github for future reference.

Behold Differences between Parse() vs Tryparse().

  • Thank you so much for the quick return! I just entered the code, there was no error, but at the moment of compilation when I start typing it appears the number I am typing and the infinity symbol (6000 ) and when I press "enter" nothing happens. What could be?

  • There is another problem, need more information, on another question, clearly showing everything important to see, with the posted has no way of knowing.

  • I understand, the strange thing is that there is no error, neither before nor at the time of the compilation. I will open another question then, showing what happens. Thanks!

Browser other questions tagged

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