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

C#使用System.Data.DataTable混合数据类型取值打印问题咨询

问题解决:DataTable混合数据类型通用取值打印方案

错误根本原因

你当前代码强制所有列都用Field<int>()取值,遇到string、bool类型列,或者值为DBNull的空单元格时,会触发强制类型转换异常。

最优解决方案:直接用DataRow索引器取值

打印场景不需要强类型转换,直接通过索引器取object类型的值,统一调用ToString()即可,同时兼容空值处理:

// 单单元格通用取值代码
object cellVal = table.Rows[行索引][列索引];
string printVal = cellVal == DBNull.Value ? "空" : cellVal.ToString();

修改后的完整代码示例

public DataTable MakeTable()
{
    DataTable table = new DataTable();
    try
    {
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("First Name", typeof(string));
        table.Columns.Add("Surname", typeof(string));
        table.Columns.Add("Permanent?", typeof(bool));
        table.Columns.Add("Salary", typeof(int));
        table.Columns.Add("Bonus", typeof(int));
        table.Columns.Add("Day Rate", typeof(int));
        table.Columns.Add("Weeks Worked", typeof(int));

        table.Rows.Add(1, "Joe", "Bloggs", true, 40000, 5000, null, null);
        table.Rows.Add(2, "John", "Smith", true, 45000, 2500, null, null);
        table.Rows.Add(3, "Clare", "Jones", false, null, null, 350, 40);

        // 标准逐行逐列打印逻辑
        for (int rowIdx = 0; rowIdx < table.Rows.Count; rowIdx++)
        {
            Console.WriteLine($"===== 第{rowIdx+1}行数据 =====");
            for (int colIdx = 0; colIdx < table.Columns.Count; colIdx++)
            {
                object cellVal = table.Rows[rowIdx][colIdx];
                string printVal = cellVal == DBNull.Value ? "无" : cellVal.ToString();
                Console.WriteLine($"{table.Columns[colIdx].ColumnName}: {printVal}");
            }
            Console.WriteLine();
        }
        return table;
    }
    catch
    {
        table.Dispose();
        throw;
    }
}

补充说明

如果确实有强类型取值的业务需求,可以先判断列的DataType属性再做对应转换,打印场景完全不需要使用Field<T>方法,上述方案已经覆盖所有数据类型的取值需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:39:03