简体   繁体   English

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

[英]Define a column as nullable in System.Data.DataTable

I need to define a System.Data.DataTable in C# VS2013;我需要在 C# VS2013 中定义一个System.Data.DataTable in one column, it may be int or null.在一列中,它可能是 int 或 null。

But I got:但我得到了:

DataSet does not support System.Nullable<>. DataSet 不支持 System.Nullable<>。

For the definition:对于定义:

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?)); 

Any ideas?有任何想法吗? Work around?解决问题?

After making the column nullable,使列可以为空后,

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

When I queried it, I got当我查询它时,我得到了

Sequence contains no elements.序列不包含任何元素。

Please see the UPDATE.请参阅更新。

UPDATE更新

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

It is a property of the DataColumn它是 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 MSDN 关于 AllowDBNull

TRY尝试

  public DataTable myDataTable
  myDataTable = new DataTable("myName");
  myDataTable.Columns.Add("ID", typeof(Int32)); 
  myDataTable.Columns.Add(new DataColumn { ColumnName = "VALUE1", DataType = typeof(int), AllowDBNull = true });
  myDataTable.Columns.Add(new DataColumn { ColumnName = "VALUE2", DataType = typeof(int), AllowDBNull = true });

this will make value columns nullable这将使值列可以为空

and at time of insert并在插入时

DataRow dr = myDataTable.NewRow();
dr["VALUE1"] = object.value1==null? (object)DBNull.Value : object.value1;

This will do what is required这将执行所需的操作

or to make it even shorter one line:或者让它更短一行:

table.Columns.Add(new DataColumn("ID", typeof(Int32)) { AllowDBNull = true });

and:和:

row["ID"] = (object) nullableId ?? DBNull.Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM