24

I have an app that loops through a fixed width text file, reads each line into a string variable and uses the .Substring() method to find data for a given field. For a given field, it checks to see if the contents are simply spaces, or if there is actually "data" in it, i.e. anything but spaces. If there is data, and that data represents a date, for instance, then DateTime.Parse() is run on that data and passed to a field of type datetime in a C# DataTable; however, if there is no data--just spaces, I want to simply pass a null value to the field. Here is a snippet of code to illustrate:

var dataTable = new DataTable();

dataTable.Columns.Add("Application_Date").DataType = Type.GetType("System.DateTime");

while (!sr.EndOfStream)
{
    string row = sr.ReadLine();

    if (row.Substring(0, 1) == "2" && row.Substring(42, 1) == "T")
    {
        DataRow dr = dataTable.NewRow();

        dr["Application_Date"] = row.Substring(124, 8) != "        " ?
                                 DateTime.Parse(row.Substring(124, 4) +
                                 "-" + row.Substring(128, 2) + "-" +
                                 row.Substring(130, 2)) :
                                 null as DateTime?;                                                         

     }
}

My problem is that when I try to run this, it throws an error saying it wants a DBNull (Cannot set Column 'Application_Date' to be null. Please use DBNull instead.)

But when I attempt to simply pass a DBNull instead, it tells me that it can't convert between DateTime and DBNull (Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime?' and 'System.DBNull')

What am I missing here?

Crono
  • 10,211
  • 6
  • 43
  • 75
Tom Miller
  • 536
  • 1
  • 4
  • 14

2 Answers2

46

You need to cast the DateTime to object to use it in the conditional:

dr["Application_Date"] = (...) ? (object)DateTime.Parse(...) : DBNull.Value;
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thank you--that did the trick! I also now understand why...thanks again! – Tom Miller Mar 07 '11 at 18:42
  • 2
    I might have missed something here, but I had the same problem and could only solve it by putting "(object)" in front of the "DBNull.Value" part of the statement (not in front of the DateTime.Parse part of the statement—as suggested by the above answer). – Andrew Jens Mar 09 '12 at 21:04
  • FYI - In VB.NET you would need to use `DataTable1.Rows(i)(j) = If(xarray(i, j), CObj(DBNull.Value))` –  Jul 10 '16 at 16:18
16

Using the null-coalescing operator:

dr["Application_Date"] = (object)nullableDateTime ?? DBNull.Value;
Saeb Amini
  • 23,054
  • 9
  • 78
  • 76