Sum in real time Textbox

0

As I can perform a multiplication in real time of two textbox and show the result in a third textbox, I'm doing it this way but the result does not come out.

private void txtPrecioUnitario_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (txtPrecioUnitario.Text.Contains('.'))
        {
            if (!char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }

            if (e.KeyChar == '\b')
                   {
                e.Handled = false;
            }
        }
        else
        {
            if (!char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }

            if (e.KeyChar =='.' || e.KeyChar =='\b')
                      {
                e.Handled = false;
            }
        }
        int total;
        total = int.Parse(txtPrecioUnitario.Text) * int.Parse(txtCantidad.Text);
        txtTotal.Text = Convert.ToString(total.ToString());

    }

    private void txtCantidad_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (txtCantidad.Text.Contains('.'))
        {
            if (!char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }

            if (e.KeyChar == '\b')
            {
                e.Handled = false;
            }
        }
        else
        {
            if (!char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }

            if (e.KeyChar == '.' || e.KeyChar == '\b')
            {
                e.Handled = false;
            }
        }
    }

    
asked by Daniel 15.09.2017 в 00:08
source

2 answers

1

Maybe if the event that triggers the function changes:

Since it has 3 text fields, you must place the event in field 3 "txtTotal" and this can be focus when entering. To avoid errors make sure that the route of the fields is such that "txtTotal" is the last. So when they fill the previous two you will find the necessary data. (plus validations and exception capture

    
answered by 15.09.2017 / 00:32
source
0

double texb1 = 0, texb2 = 0;

    public void suma(double n1, double n2)
    {
        double sum = n1 + n2;
        textBox3.Text = sum.ToString();  
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        texb1 = Double.Parse (textBox1.Text.ToString());
        suma(texb1, texb2);
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        texb2 = double.Parse(textBox2.Text.ToString());
        suma(texb1, texb2);
    }

could be like that no matter where you insert the data since the event you trigger them when typing a character and it is necessary to put something in order to validate that they are only numbers I hope you greet them

    
answered by 15.09.2017 в 00:31