键入数值时自动将结果显示为文本

Automatically show the result to a text when ever a numeric value is being typed

我有三个文本框,第一个价格文本框有一个常量值,而我必须向第二个输入一个值,第三个显示这两个值相乘的结果 textboxes

所以我想在这里做的是每当我在数量文本框中输入一个值,例如10,小计会自动显示结果,当我删除它时,它会变回零

到目前为止,这是我创建事件 KeyDown 的代码

 private void txtQuantity_KeyDown(object sender, KeyEventArgs e)
        {
            KeysConverter kc = new KeysConverter();
            string keyChar = kc.ConvertToString(e.KeyCode);
            double quantity = Convert.ToDouble(keyChar);
            double price = Convert.ToDouble(txtPrice.Text);
            double subtotal = quantity * price;
            txtSubtotal.Text = subtotal.toString();
        }

这是有效的,但是当我在第一个数字旁边输入另一个数字时,它得到的是第二个数字的值而不是整个数字的值,当我输入退格键时它得到一个错误 error

对于 _KeyDown 事件,您可以尝试使用 _TextChanged 来实现目标:让控件为 txtQtytxtPricetxtTotal,其中价格被禁用并保持恒定值。

    private void txtQty_TextChanged(object sender, EventArgs e)
    {
        double price, qty, total;
        double.TryParse(txtPrice.Text, out price);
        if (!double.TryParse(txtQty.Text, out qty))
        {
            txtTotal.Text = "0.00";
            txtQty.BackColor = Color.Red; //indicates wrong input
        }
        else
        {               
            total = price * qty;
            txtTotal.Text = total.ToString("#0.00");
        }
    }

注意:在上面的代码片段中,我提供了一个附加功能;如果用户输入错误,txtQty 的背景颜色会变为 red

倒霉的是最佳答案。

但是,我将如何使用您现有的事件处理程序进行操作:

var quantityInput = sender as TextBox;
double quantity = 0;
double price = 0;
double.TryParse(txtPrice.Text, out price);

if (quantityInput != null)
{
    double.TryParse(quantityInput.Text.Trim(), out quantity);
}

txtSubtotal.Text = quantity * price;