Table is nullable DateTime, but DataSet throws an exception?

Viewed 51201

I'm attempting to use the DataSet designer to create a datatable from a query. I got this down just fine. The query used returns a nullable datetime column from the database. But, when it gets around to this code:

DataSet1.DataTable1DataTable table = adapter.GetData();

This throws a StrongTypingException from:

[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public System.DateTime event_start_date {
    get {
        try {
            return ((global::System.DateTime)(this[this.tableDataTable1.event_start_dateColumn]));
        }
        catch (global::System.InvalidCastException e) {
            throw new global::System.Data.StrongTypingException("The value for column \'event_start_date\' in table \'DataTable1\' is DBNull.", e);
        }
    }
    set {
        this[this.tableDataTable1.event_start_dateColumn] = value;
    }
}

How do I use the designer to allow this column to be Nullable?

9 Answers

In DataSet Designer, use System.Object data type instead of System.DateTime and set NullValue to (Null) and DefaultValue to <DBNull> and when it is needed, convert it such as:

var row1 = dateSet1.table1.FirstOrDefault();
if (row1 == null)
    return;
DateTime? date = (DateTime?) row1.ObjectDate;
Related