Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a column as nullable in System.Data.DataTable

I need to define a System.Data.DataTable in C# VS2013; in one column, it may be int or null.

But I got:

  DataSet does not support 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();
like image 401
Lily Avatar asked Dec 03 '16 23:12

Lily


Video Answer


1 Answers

It is a property of the 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

like image 69
Steve Avatar answered Oct 18 '22 20:10

Steve