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

如何在DataTable中为INTEGER类型列设置NULL值?

解决方案

方法一:使用可空整数类型(int?)

C# 中值类型 int 无法直接赋值为 null,但可空值类型 int? 支持存储 null。你可以先通过它暂存数据,再转换为 DataTable 接受的格式:

int? nullableInt = null;
if (t.Rows.Count > 0)
{
    nullableInt = Convert.ToInt32(t.Rows[0][1]);
}

// 根据可空变量是否有值,传入对应内容
t.Rows.Add(new object[] { "目标字符串", nullableInt.HasValue ? nullableInt.Value : DBNull.Value });

方法二:直接在添加行时做条件判断(无需额外变量)

跳过定义单独的整数变量,直接在 Rows.Add 方法中根据条件决定传入 DBNull.Value 或具体数值,写法更紧凑:

// 先判断并生成对应值
object intColumnValue = t.Rows.Count > 0 ? Convert.ToInt32(t.Rows[0][1]) : DBNull.Value;
t.Rows.Add(new object[] { "目标字符串", intColumnValue });

或者更简洁的 inline 写法:

t.Rows.Add(new object[] { 
    "目标字符串", 
    t.Rows.Count > 0 ? Convert.ToInt32(t.Rows[0][1]) : (object)DBNull.Value 
});

关键注意事项

确保 DataTable 的整数列允许存储空值,否则传入 DBNull.Value 会触发错误。创建列时需设置 AllowDBNull 属性为 true:

DataColumn intColumn = new DataColumn("你的整数列名", typeof(int));
intColumn.AllowDBNull = true;
t.Columns.Add(intColumn);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:55:05