You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

双精度值文本框为空时需提示,代码第二条件报错求助

问题分析与解决方案

嘿,我一眼就瞅出问题所在啦!你现在的代码逻辑有个致命的顺序问题:在检查Txtamount是否为空之前,你已经执行了double.Parse(Txtamount.Text)。如果Txtamount是空的,这行代码会直接抛出FormatException异常,程序根本走不到后面的else if判断,自然触发不了你写的空值提示。

修正方案1:调整执行顺序(基础版)

先完成所有空值校验,确认输入合法后再进行类型转换:

acno = Txtacc.Text;
// 先检查账号输入
if (string.IsNullOrEmpty(this.Txtacc.Text)) {
    MessageBox.Show("You have not entered account number, Please Enter it...!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
} 
// 再检查金额输入是否为空
else if (string.IsNullOrEmpty(this.Txtamount.Text)) {
    MessageBox.Show("You have not entered amount, Please Enter it..!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
} 
// 确认输入都不为空后,再转换为double类型
else {
    recoverymoney = double.Parse(Txtamount.Text);
    // 这里可以添加后续的业务逻辑,比如提交数据等
}

修正方案2:使用double.TryParse(健壮版)

如果想同时处理用户输入非数字的情况(比如输入字母、符号),推荐用TryParse方法,它不会抛出异常,而是返回布尔值表示转换是否成功:

acno = Txtacc.Text;
if (string.IsNullOrEmpty(this.Txtacc.Text)) {
    MessageBox.Show("You have not entered account number, Please Enter it...!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
} 
else if (string.IsNullOrEmpty(this.Txtamount.Text)) {
    MessageBox.Show("You have not entered amount, Please Enter it..!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
} 
// 检查金额是否为有效的数字格式
else if (!double.TryParse(Txtamount.Text, out recoverymoney)) {
    MessageBox.Show("Please enter a valid numeric amount!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
} 
else {
    // 此时recoverymoney已经是有效的双精度数值,可正常使用
}

这样调整后,空值提示就能正常触发,还能避免不必要的异常哦!

内容的提问来源于stack exchange,提问作者Roshan Abrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:00:17