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

如何将DataGrid文本框中的内容转换为Decimal类型?

实现方案

一、直接从DataGridView单元格转换为decimal

如果是已经将内容以字符串形式存入DataGridView的情况,使用decimal.TryParse做安全转换,避免格式错误导致程序崩溃:

// 示例:读取指定行的AccBalance列(示例为第10列,可根据你的实际列索引调整)内容转decimal
int targetRowIndex = 0; // 替换为你要读取的行索引
int accBalanceColumnIndex = 10; // 替换为AccBalance对应的实际列索引

if (dataGridView2.Rows[targetRowIndex].Cells[accBalanceColumnIndex].Value != null)
{
    string cellContent = dataGridView2.Rows[targetRowIndex].Cells[accBalanceColumnIndex].Value.ToString();
    if (decimal.TryParse(cellContent, out decimal result))
    {
        // 转换成功,result即为decimal类型的值,可直接用于业务逻辑
    }
    else
    {
        // 转换失败的兜底逻辑,比如赋值默认值、提示用户内容格式错误
    }
}

如果单元格内容包含货币符号、千位分隔符等特殊格式,可指定格式规则转换:

using System.Globalization;

// 适配货币格式的转换
decimal.TryParse(cellContent, 
    NumberStyles.Currency | NumberStyles.Number, 
    CultureInfo.CurrentCulture, 
    out decimal result);

二、优化数据加载逻辑,从根源避免转换问题

你当前的加载代码将所有字段都转为字符串存入DataGridView,不仅容易引发转换错误,还存在SQL注入风险,优化后的代码如下:

public void LoadStock() {
    int i = 0;
    dataGridView2.Rows.Clear();
    // 使用参数化查询,避免SQL注入漏洞
    string query = "select * from vwStockIn where RefNo like @RefNo and Status like 'Pending'";
    
    cn.Open();
    using (SqlCommand cm = new SqlCommand(query, cn))
    {
        cm.Parameters.AddWithValue("@RefNo", txtRefNo.Text);
        using (SqlDataReader dr = cm.ExecuteReader())
        {
            while (dr.Read()) {
                i++;
                // 数值类型字段直接读取为对应类型,不要转为字符串
                decimal accBalance = dr.GetDecimal(dr.GetOrdinal("AccBalance"));
                dataGridView2.Rows.Add(
                    i, 
                    dr[0].ToString(), 
                    dr[1].ToString(), 
                    dr[2].ToString(), 
                    dr[3].ToString(), 
                    dr[4].ToString(), 
                    dr[5].ToString(), 
                    dr[6].ToString(), 
                    dr[7].ToString(), 
                    dr["CompanyName"].ToString(), 
                    accBalance // 直接存入decimal类型值
                );
            }
        }
    }
    cn.Close();
}

优化后,后续读取单元格内容时可直接强转,不需要解析字符串:

decimal accBalance = (decimal)dataGridView2.Rows[targetRowIndex].Cells[accBalanceColumnIndex].Value;

内容的提问来源于stack exchange,提问作者John Chukwudi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:24:05