Textbox_changed is accumulating the sum value c#

Asked

Viewed 411 times

3

I’m using the event textBox_Changed and when I type a value into the field, another textBox should receive this value, but this other textBox called ValorTotalVenda is accumulating this amount.

private void textBox4_TextChanged(object sender, EventArgs e)
{
    if (textBox4.Text != "")
    {
         venda.ValorAcrescimo = Convert.ToDecimal(textBox4.Text);
         venda.ValorTotalVenda += venda.ValorAcrescimo;
         textBox6.Text = Convert.ToString(venda.ValorTotalVenda);
     }
}
  • Dude, there’s no textbox in your code called Valortotalvenda. It has a property (probably Decimal) and you add the value of the property Valoracrescimo. If you want the textBox6 to receive the value typed in the textBox4 you should do only textBox6.Text = textBox4.Text.

2 answers

4


Are you changing the value of the property Valuemost, wouldn’t it be easier just to add the values to the textbox6? the way this writing or you define a global variable for the initial sale value or you do it this way.

if (textBox4.Text != "")
        {
            venda.ValorAcrescimo = Convert.ToDecimal(textBox4.Text);
            textBox6.Text = Convert.ToString(venda.ValorTotalVenda + venda.ValorAcrescimo);
        }

1

Every character typed in textoBox4 is added to the value of the variable ValorTotalVenda, which seems strange to me. You asked to display in textbox6 the sum value, since the operador + with numbers will perform an addition, not a concatenation.

private void textBox4_TextChanged(object sender, EventArgs e)
    {
        if (textBox4.Text != "")
        {
            venda.ValorAcrescimo = Convert.ToDecimal(textBox4.Text);
            venda.ValorTotalVenda += venda.ValorAcrescimo;
            //Mostra o valor somado
            textBox6.Text = venda.ValorTotalVenda.ToString();
            //ou, mostra inteiramente o conteúdo que está sendo digitado no textbo4
            textBox6.Text = textBox4.Text;
        }
    }

In addition to the code, see these posts as a complement:

What is the difference between the "+" and "&" operators when concatenating strings?
What is the most appropriate way to concatenate strings?

Browser other questions tagged

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