validate TextChange function subtraction of numbers

0

Hello good morning to all, I have to do a calculation (calculate the returned to deliver) between a total and cash delivered, I am working with decimal values. The calculation operation is performing well, I enter the values and it automatically shows me the result in a label (I use the TextChanged event of the label, where I call the function that makes the calculation) the issue is that when I delete some of the values give the textbox, the program falls and shows me this message:

Obviously, what I need is to validate that when the values are deleted, the event that makes the calculation is not triggered, but I do not give an idea how to do it, I had tried to check the empty fields, but it did not work (see in image the code that was testing).

I am grateful for your comments, greetings to all.

Method to do the calculation:

private void calcularVuelto()
    {
        if (string.IsNullOrEmpty(txtMontoCancelar.Text) || string.IsNullOrEmpty(txtEfectivo.Text))
        {
            this.txtMontoCancelar.Text = "00.000";
            this.txtEfectivo.Text = "00.000";
        }
        else
        {
            total = decimal.Parse(this.txtMontoCancelar.Text);
            efectivo = decimal.Parse(this.txtEfectivo.Text);             
            vuelto = total - efectivo;
            //txtVuelto.Text = Convert.ToDecimal(vuelto).ToString();
            lblVuelto.Text = Convert.ToDecimal(vuelto).ToString();
        }           
    }

and in the leave event of the label where I show the result:

this.calculaVuelta ();

    
asked by Nicolas Ezequiel Almonacid 20.08.2018 в 17:38
source

2 answers

0

According to what I could see by your method you should assign the TextChanged event to the TextBox after that in each function you should invoke the calculateReturn () method; can be as follows:

OnlyDecimales_KeyPress would be assigned to the KeyPress of each TextBox

decimal total;
decimal efectivo;
decimal vuelto;

private void OnlyDecimales_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) || ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1));
}

private void txtMontoCancelar_Leave(object sender, EventArgs e)
{
    calcularVuelto();
}

private void txtEfectivo_Leave(object sender, EventArgs e)
{
    calcularVuelto();
}

private void calcularVuelto()
{
    txtMontoCancelar.Text = decimal.TryParse(txtMontoCancelar.Text.Replace('.', ','), out total) ? total.ToString() : "0";
    txtEfectivo.Text = decimal.TryParse(txtEfectivo.Text.Replace('.', ','), out efectivo) ? efectivo.ToString() : "0";
    vuelto = total - efectivo;
    lblVuelto.Text = string.Format("{0:00.000}", vuelto);
}
    
answered by 20.08.2018 / 20:02
source
0

Try the following.

if(txtMontoCancelar.Text == "" || txtEfectivo.Text == "")

I hope I help you.

    
answered by 20.08.2018 в 17:53