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

如何修复DataGridView事件中出现的‘Input string was not in a correct format.’错误?

解决“Input string was not in a correct format”格式错误

错误信息

'Input string was not in a correct format.'

问题定位

错误根源在你调用double.Parse()和int.Parse()时,传入的字符串无法被解析为对应数值类型。问题行里有两处关键错误:

  1. 单元格取值方式错误:
    你直接对Cells[6]和Cells[7]调用ToString(),这返回的是DataGridViewCell对象的类型字符串(比如System.Windows.Forms.DataGridViewTextBoxCell),而非单元格内的实际数值内容,必然导致解析失败。

  2. 未处理空值与非法格式:
    即使正确获取单元格值,若内容为空、包含非数字字符,Parse()也会抛出格式错误。

修正代码

private void dgvProduct_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    string colName = dgvProduct.Columns[e.ColumnIndex].Name;
    if(colName == "Edit")
    {
        var targetRow = dgvProduct.Rows[e.RowIndex];
        // 安全获取单元格值,空值转为空字符串
        string productInfo = targetRow.Cells[1].Value?.ToString() ?? string.Empty;
        string priceText = targetRow.Cells[6].Value?.ToString() ?? string.Empty;
        string qtyText = targetRow.Cells[7].Value?.ToString() ?? string.Empty;
        
        // 用TryParse替代Parse,避免直接抛出异常
        if(double.TryParse(priceText, out double productPrice) && int.TryParse(qtyText, out int productQty))
        {
            Qty qtyDialog = new Qty(cashier);
            qtyDialog.ProductDetails(productInfo, productPrice, cashier.lblTransactionNo.Text, productQty);
            qtyDialog.ShowDialog();
        }
        else
        {
            // 格式错误时给出友好提示
            MessageBox.Show("价格或数量格式无效,请检查表格数据");
        }
    }
}

改进说明

  • 用Value?.ToString() ?? string.Empty避免空值引发的NullReferenceException
  • 替换Parse为TryParse,可以优雅处理格式非法的情况,同时返回解析结果
  • 提取变量让代码更易读,调试时可直接查看每个单元格的实际值

内容的提问来源于stack exchange,提问作者Nikola Stojiljkovic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:22:43