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

VB写入Access数据库时SubTotal字段报Input string was not in correct format错误

问题原因

Input string was not in a correct format 错误触发在类型转换阶段,和Access字段配置无关:你代码中直接调用Convert.ToDecimal()、Convert.ToInt32()方法转换文本框内容时,输入的字符串不符合目标类型的格式规则,直接抛出异常。

解决方案

1. 增加输入合法性校验,避免强转报错

不要直接使用Convert类做强制转换,改用TryParse系列方法做安全转换,转换失败先终止流程并提示用户修改输入:

' 提前引入命名空间
Imports System.Globalization

' 数据写入前先做全量字段校验
Dim orderNo As Integer
If Not Integer.TryParse(txtorderno.Text.Trim(), orderNo) Then
    MessageBox.Show("订单号请输入合法整数")
    Exit Sub
End If

Dim subTotal As Decimal
' 可选指定InvariantCulture强制匹配小数点分隔符,规避系统区域设置影响
If Not Decimal.TryParse(txtsubtotal.Text.Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, subTotal) Then
    MessageBox.Show("小计请输入合法数值")
    Exit Sub
End If

Dim vat As Integer
If Not Integer.TryParse(txtvat.Text.Trim(), vat) Then
    MessageBox.Show("VAT请输入合法整数")
    Exit Sub
End If

Dim fullAmount As Integer
If Not Integer.TryParse(txttotal.Text.Trim(), fullAmount) Then
    MessageBox.Show("总金额请输入合法整数")
    Exit Sub
End If

Dim discount As Integer
If Not Integer.TryParse(txtdiscount.Text.Trim(), discount) Then
    MessageBox.Show("折扣请输入合法整数")
    Exit Sub
End If

' 校验完成后再赋值参数
With cmd.Parameters
    .Add("@OrderNo", OleDbType.Integer).Value = orderNo
    .Add("@SubTotal", OleDbType.Decimal).Value = subTotal
    .Add("@VAT", OleDbType.Integer).Value = vat
    .Add("@FullAmount", OleDbType.Integer).Value = fullAmount
    .Add("@Discount", OleDbType.Integer).Value = discount
    .Add("@CustomerID", OleDbType.VarChar).Value = ComboBox2.Text.Trim()
    .Add("@Employees", OleDbType.VarChar).Value = ComboBox1.Text.Trim()
End With

2. 增加输入限制减少报错概率

给数值类输入文本框添加按键事件拦截,只允许输入数字、小数点和删除键,避免用户输入汉字、字母、特殊符号等非法内容。


内容的提问来源于stack exchange,提问作者Hamza Asim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:39:02