Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing null into a DataTable from a single line conditional statement parsing string values

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?

like image 463
Tom Miller Avatar asked Mar 07 '11 18:03

Tom Miller


2 Answers

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

dr["Application_Date"] = (...) ? (object)DateTime.Parse(...) : DBNull.Value; 
like image 105
SLaks Avatar answered Sep 19 '22 11:09

SLaks


Using the null-coalescing operator:

dr["Application_Date"] = (object)nullableDateTime ?? DBNull.Value;
like image 45
Saeb Amini Avatar answered Sep 19 '22 11:09

Saeb Amini