如何立即计算文本框中的两个数字,当我删除数字时结果变成了什么?

时间:2017-03-30 18:32:34

标签: c#

如何立即计算文本框中的两个数字,当我从任何文本框中删除数字时结果会变化? 这是我的代码

        private void expenses_KeyDown(object sender, KeyEventArgs e)
    {
        if (expenses.Text != string.Empty)
        {
            decimal Pprice = Convert.ToDecimal(buyTotal.Text);
            decimal expens = Convert.ToDecimal(expenses.Text);
            decimal final = Pprice + expens;
            buyTotal.Text = final.ToString();
        }
    }

但是当我使用退格键并从任何文本框中删除号码并写入另一个号码时我收到了错误的结果,我想现在我很清楚我想要在费用中键入数字。文本它添加到buyTotal.Text并且当我删除数字时我输入它计算结果

2 个答案:

答案 0 :(得分:1)

下面的代码应该足以计算两个数字总和:

private void expenses_KeyDown(object sender, KeyEventArgs e)
{
    try
    {
        if (expenses.Text != string.Empty)
        {
            double Pprice = Convert.ToDouble(buyTotal.Text);
            double expens = Convert.ToDouble(expenses.Text);
            double final = Pprice + expens;
            buyTotal.Text = final.ToString("0.00");
        }
        else
        {
            buyTotal.Text="0.00";
        }
    }
    catch(Exception exc)
    {
        buyTotal.Text="0.00";
    }
}

答案 1 :(得分:1)

KeyUp代替KeyDown,因为您的输入值会在textbox事件后写入KeyDown

请检查:

private void expenses_KeyUp(object sender, KeyEventArgs e)
{
    if (expenses.Text != string.Empty)
    {
        decimal Pprice = Convert.ToDecimal(buyTotal.Text);
        decimal expens = Convert.ToDecimal(expenses.Text);
        decimal final = Pprice + expens;
        buyTotal.Text = final.ToString();
    }
    if (e.KeyCode == Keys.Back)
    {
        buyTotal.Text = (from DataGridViewRow row in dataGridView1.Rows where row.Cells[6].FormattedValue.ToString() != string.Empty select Convert.ToDecimal(row.Cells[6].FormattedValue)).Sum().ToString();
    }
}