如何更新“更改”?当我减去总额和总付费时,文本框? [英] How can I update the "change" textbox when I subtract grand total and total paid?

查看:43
本文介绍了如何更新“更改”?当我减去总额和总付费时,文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个文本框,TotalPaid,GrandTotal和Change。根据MSDN,我能够找到2种合适的方法,验证和textchanged。使用验证方法它不会将值直接传递给更改文本框。另一方面,使用textchanged,当我清空文本框时,它会给我一个例外。关于如何执行此任务的任何想法?



异常:

输入字符串的格式不正确。



我的尝试:



I have 3 textboxes, TotalPaid, GrandTotal and Change. Accordingly to MSDN, i was able to find 2 suitable methods, "validating" and "textchanged". With the validating method It would not pass the values directly to "Change" textbox. On the other hand, with the textchanged it gives me an exception when i empty the textbox. Any ideias on how to execute this task?

Exception:
Input string was not in a correct format.

What I have tried:

private void txtTotalPaid_Validating(object sender, CancelEventArgs e)
{
    decimal value1, value2, result = 0;
    value1 = Convert.ToDecimal(txtTotalPaid.Text);
    value2 = Convert.ToDecimal(txtGrandTotal.Text);
    result = value1 - value2;
    txtTroco.Text = result.ToString();
}



在看到它不能用于验证后,在Textchanged方法上使用相同的代码。


Used the same code on the Textchanged method after seeing that it wouldn't work with validating.

推荐答案

首先不使用Convert作为用户输入 - 如果用户输入错误,它将始终抛出异常。

相反,使用decimal.TryParse:

Start by not using Convert for user input - it will always throw an exception if the user gets it wrong.
Instead, use decimal.TryParse:
decimal totPaid;
if (!decimal.TryParse(txtTotalPaid.Text, out totPaid))
   {
   // Report input problem to user
   return;
   }
decimal totGrand;
...

然后在构建结果时使用经过验证的值,它应该有效:

Then use the validated values when you build your result and it should work:

txtTroco.Text = (totPaid - totGrand).ToString();



这应该在Validating事件中有效。


That should work in the Validating event.


这篇关于如何更新“更改”?当我减去总额和总付费时,文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆