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

C# MSSQL中DataGridView插入Invoice表报错:输入字符串格式不正确

嘿,这个「输入字符串格式不正确」的错误在处理DataGridView数值输入时真的太常见了,我来帮你一步步排查和解决!

核心原因分析

这个报错几乎100%是从DataGridView读取Quantity或Item Total时,字符串转数值类型失败导致的,常见触发场景包括:

  • 输入了非数字字符(比如空格、字母、中文逗号/小数点)
  • 单元格是空值/空字符串,直接用Parse方法转换
  • 不小心在数字前后加了空格,转数值时被当成非法字符
排查步骤
  1. 定位报错代码行:在提交按钮的点击事件里,找到你从DataGridView提取Quantity和Item Total的代码(比如int qty = int.Parse(xxx)),这就是报错的源头。可以用调试模式看具体哪个单元格的Value有问题,或者用try-catch捕获错误信息。
  2. 检查输入内容:确认用户输入的数值是不是纯英文数字(注意是英文小数点,不能用中文符号),有没有不小心输入空格。
  3. 检查单元格Value状态:DataGridView的单元格Value可能是DBNull.Value或者null,直接ToString()会得到空字符串,转数值必然报错。
具体解决方法

1. 用安全转换替代强制Parse

放弃容易报错的int.Parse/decimal.Parse,改用TryParse方法,既能避免崩溃,还能给用户友好提示:

private void btnSubmit_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        // 跳过DataGridView默认的空新行
        if (row.IsNewRow) continue;

        // 处理Quantity字段
        string qtyStr = row.Cells["Quantity"].Value?.ToString().Trim() ?? string.Empty;
        if (!int.TryParse(qtyStr, out int quantity))
        {
            MessageBox.Show($"第{row.Index+1}行的Quantity输入无效,请输入整数!");
            row.Cells["Quantity"].Selected = true; // 定位到错误单元格
            return;
        }

        // 处理Item Total字段
        string totalStr = row.Cells["ItemTotal"].Value?.ToString().Trim() ?? string.Empty;
        if (!decimal.TryParse(totalStr, out decimal itemTotal))
        {
            MessageBox.Show($"第{row.Index+1}行的Item Total输入无效,请输入正确的数字!");
            row.Cells["ItemTotal"].Selected = true;
            return;
        }

        // 这里写你的数据库插入逻辑(比如插入Invoice表)
        // ...
    }
}

2. 从源头限制输入

给Quantity和Item Total列添加输入限制,只允许数字和必要的小数点,彻底避免非法输入:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    // 判断当前编辑的是Quantity或Item Total列
    if (dataGridView1.CurrentCell.OwningColumn.Name == "Quantity" || 
        dataGridView1.CurrentCell.OwningColumn.Name == "ItemTotal")
    {
        TextBox editBox = e.Control as TextBox;
        if (editBox != null)
        {
            // 先移除旧事件,避免重复绑定
            editBox.KeyPress -= NumericOnly_KeyPress;
            editBox.KeyPress += NumericOnly_KeyPress;
        }
    }
}

private void NumericOnly_KeyPress(object sender, KeyPressEventArgs e)
{
    TextBox currentBox = sender as TextBox;
    // 允许数字、退格键;Item Total允许一个小数点
    if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
    {
        if (e.KeyChar == '.' && currentBox.Text.IndexOf('.') == -1)
        {
            return; // 允许输入第一个小数点
        }
        e.Handled = true; // 阻止非法字符输入
    }
}

3. 检查自动填充的Item Rate字段

如果Item Rate是从数据库读取的数值类型,确保绑定到DataGridView时是数值类型而非字符串。比如从数据库读取时用reader.GetDecimal("itemrate"),而不是reader["itemrate"].ToString(),这样后续如果需要用Quantity*Rate计算Total,也不会出现类型转换问题。

4. 跳过空新行

如果你的DataGridView允许用户添加新行(默认开启),提交时一定要跳过IsNewRow的行,否则会读取到空值导致转换错误,上面的示例代码已经包含了这个判断。

内容的提问来源于stack exchange,提问作者Sijo George Oommen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:06:05