C#差额计算时出现‘输入字符串格式不正确’错误的解决求助
问题解决:Input string was not in a correct format. 异常处理
这个错误是double.Parse方法抛出的——当文本框内容是空字符串、包含非数字字符,或者格式不符合double类型要求时,就会触发这个异常。你提到数据能成功存入数据库,说明插入操作时文本框内容是有效的,但异常大概率出现在文本框内容变化的其他时机:比如用户删除输入内容、清空文本框时,或者插入完成后调用Clear()方法清空文本框,触发了txtDeposit_TextChanged事件,此时txtPrice或txtDeposit为空,执行解析就会报错。
以下是具体修复方案:
1. 安全解析数字:用double.TryParse替代double.Parse
修改文本框的TextChanged事件代码,只有当两个文本框的内容都能成功解析为double时,才计算余额:
private void txtDeposit_TextChanged(object sender, EventArgs e) { double value1, value2, result = 0; // 只有两个文本框都能解析成功时,才计算余额 if (double.TryParse(txtPrice.Text, out value1) && double.TryParse(txtDeposit.Text, out value2)) { result = value1 - value2; txtBalance.Text = result.ToString(); } else { // 解析失败时清空余额框,避免显示无效值 txtBalance.Text = string.Empty; } }
同样,插入数据库的代码也建议用TryParse做前置验证,确保不会因为输入异常导致插入失败(虽然你当前插入成功,但可以避免后续潜在问题):
// 先验证输入有效性 if (!double.TryParse(txtPrice.Text, out double price) || !double.TryParse(txtDeposit.Text, out double deposit) || !double.TryParse(txtBalance.Text, out double balance)) { MessageBox.Show("请输入有效的数字格式!", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } cn.Open(); cm = new SqlCommand("insert into tblLayby (brid, cname, phone, email, pdesc, price, deposit, balance, date) values(@brid, @cname, @phone, @email, @pdesc, @price, @deposit, @balance, @date)", cn); cm.Parameters.AddWithValue("@brid", brid); cm.Parameters.AddWithValue("@cname", cboClient.Text); cm.Parameters.AddWithValue("@phone", txtPhone.Text); cm.Parameters.AddWithValue("@email", txtEmail.Text); cm.Parameters.AddWithValue("@pdesc", cboProduct.Text); cm.Parameters.AddWithValue("@price", price); cm.Parameters.AddWithValue("@deposit", deposit); cm.Parameters.AddWithValue("@balance", balance); cm.Parameters.AddWithValue("@date", date.Value); cm.ExecuteNonQuery(); cn.Close(); MessageBox.Show("Layby has been successfully saved!", title, MessageBoxButtons.OK, MessageBoxIcon.Information); Clear();
2. 处理Clear()方法触发的事件异常
如果Clear()方法会清空所有文本框,那么清空txtDeposit时会触发txtDeposit_TextChanged事件,此时txtPrice为空就会触发解析异常。可以在清空时临时移除事件绑定,完成后再重新绑定:
private void Clear() { // 先移除事件绑定,避免清空时触发解析异常 txtDeposit.TextChanged -= txtDeposit_TextChanged; // 执行清空操作 txtPrice.Text = string.Empty; txtDeposit.Text = string.Empty; txtBalance.Text = string.Empty; cboClient.Text = string.Empty; txtPhone.Text = string.Empty; txtEmail.Text = string.Empty; cboProduct.Text = string.Empty; date.Value = DateTime.Now; // 重新绑定事件 txtDeposit.TextChanged += txtDeposit_TextChanged; }
内容的提问来源于stack exchange,提问作者Abu Hashmah
相关产品推荐
相关产品推荐

