TextEdit控件Value属性减法运算结果错误,求排查解决
问题分析与修复方案
核心问题
你的代码在KeyPress事件中执行减法,但这个事件每输入一个字符就触发一次,导致Costo.Value被反复修改,完全偏离了“输入完成后计算一次差值”的预期。比如输入50-50的过程会触发多次计算:
- 输入第一个
5:precio1frm.Value=5,Costo.Value=5-0=5(假设初始值为0) - 输入
0:precio1frm.Value=50,Costo.Value=50-5=45 - 输入
-:此时控件未完成数值解析,precio1frm.Value仍为50,Costo.Value=50-45=5 - 输入第二个
5:precio1frm.Value变为5(因减号导致输入内容解析异常),Costo.Value=5-5=0,后续输入0又会触发一次计算,最终得到错误结果。
另外,代码逻辑Costo.Value = precio1frm.Value - Costo.Value本身是用Costo的当前值参与计算,这不是常规的“两个固定数值相减”,而是每次触发都让Costo的值被覆盖为差值,这也是错误的根源。
修复方案
1. 选择正确的触发事件
放弃KeyPress,改用Validated或LostFocus事件,确保输入完成后仅计算一次:
private void precio1frm_Validated(object sender, EventArgs e) { // 示例:假设需求是 Costo = precio1frm的值 - 固定值(比如50) decimal fixedValue = 50; Costo.Value = precio1frm.Value - fixedValue; // 如果是两个输入框相减,比如Costo = precio1frm - precio2frm // Costo.Value = precio1frm.Value - precio2frm.Value; }
2. 若需按键触发,限定触发时机
如果必须在按键时计算,仅在按下回车键(确认输入完成)时执行:
private void precio1frm_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Enter) { decimal fixedValue = 50; Costo.Value = precio1frm.Value - fixedValue; e.Handled = true; // 阻止回车键默认行为 } }
3. 修正计算逻辑
如果你的需求是保留Costo的初始值作为减数,需提前保存初始值,避免用当前值参与计算:
private decimal _initialCosto; // 窗体初始化时保存初始值 private void YourForm_Load(object sender, EventArgs e) { _initialCosto = Costo.Value; } private void precio1frm_Validated(object sender, EventArgs e) { Costo.Value = precio1frm.Value - _initialCosto; }
验证测试
修改后,输入50并离开输入框(或按回车键),Costo.Value会正确得到50-50=0,符合预期。
内容的提问来源于stack exchange,提问作者jebus
相关产品推荐
相关产品推荐

