如何在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
相关产品推荐
相关产品推荐

