c# - 在 System.Data.DataTable 中将列定义为可为空

标签 c# types datatable nullable

我需要在 C# VS2013 中定义一个 System.Data.DataTable;在一列中,它可能是 int 或 null。

但是我得到了:

DataSet does not support System.Nullable<>.

对于定义:

public DataTable myDataTable
myDataTable = new DataTable("myName");
myDataTable.Columns.Add("ID", typeof(Int32)); 
myDataTable.Columns.Add("value1", typeof(Int32?)); // run time error 
myDataTable.Columns.Add("value2", typeof(Int32?)); 

有什么想法吗?变通?

在使列可以为空之后,

DataColumn dc = myDataTable.Columns.Add("value1", typeof(Int32));
dc.AllowDBNull = true;

当我查询它时,我得到了

Sequence contains no elements.

请查看更新。

更新

int? result = (from r in myDataTable.AsEnumerable()
               where r.Field<Int32>("ID") == givenID
                   && r.Field<Int32?>("value1") == givenValue1
               select r.Field<Int32>("value2")).First();

最佳答案

它是DataColumn的一个属性

public DataTable myDataTable
myDataTable = new DataTable("myName");
myDataTable.Columns.Add("ID", typeof(Int32)); 
DataColumn dc = myDataTable.Columns.Add("value1", typeof(Int32)); 
dc.AllowDBNull = true;

MSDN about AllowDBNull

关于c# - 在 System.Data.DataTable 中将列定义为可为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40953738/

相关文章:

c# - 更好的淡化 winform 的算法

haskell - 是否可以在 Haskell 中否定类型参数约束?

swift - 类类型属性不应该有 static 关键字吗?

c# - 不能向没有列的 DataGridView 控件添加任何行。必须先添加列

c# - Visual Studio 2015 System.Exception 包无法注册。错误 0x80070005 Xaml 问题

java - 如何通过查询获取sqlite表中特定名称的数量

c# - 从第一列不包含的数据表中删除行(一些字符串)

vb.net - 如何对数据表进行排序

c# - IIS 7.5 无法使用代码隐藏文件加载自定义 HTTP 处理程序

C++ 原始数据类型 : how to read unsigned 30 bits