3xGuy
3xGuy

Reputation: 2559

reader.GetDateTime(null)

I'm working on an application that will read from a stored procedure and put into the worksheet. My problem is that when I run into a null it isn't handled in the code.

               while (reader.Read())
               {

                   ws.Cells[i, 1] = reader.GetString(0);
                   ws.Cells[i, 2] = reader.GetString(1);
                   ws.Cells[i, 3] = reader.GetString(2);
                   ws.Cells[i, 4] = reader.GetString(3);
                   ws.Cells[i, 5] = reader.GetString(4);
                   ws.Cells[i, 6] = reader.GetString(5);
                   ws.Cells[i, 7] = reader.GetDecimal(6);
                   ws.Cells[i, 8] = reader.GetDateTime(7);
                   ws.Cells[i, 9] = reader.GetDecimal(8);
                   ws.Cells[i, 10] = reader.GetDecimal(9);
                   ws.Cells[i, 11] = reader.GetDecimal(10);
                   ws.Cells[i, 12] = reader.GetDecimal(11);
                   ws.Cells[i, 13] = reader.GetDateTime(12);
                   ws.Cells[i, 13] = reader.GetDateTime(13);
                   i++;
               }
               reader.Close();

if someone could explain how to handle this so that we just leave the cell null; thanks!!

Upvotes: 5

Views: 8035

Answers (4)

Praveen Paulose
Praveen Paulose

Reputation: 5771

You can use reader.IsDBNull to check if a value is null and write conditional logic in your code.

if (reader.IsDBNull(12)) {
    ws.Cells[i, 13] = "";
} else {
    ws.Cells[i, 13] = reader.GetDateTime(12);
}

Upvotes: 7

Padraic
Padraic

Reputation: 667

I would create an extension method to do this.

Something like:

static class DataReaderExtensions
{
    public static DateTime? TryGetDateTime(this DataTableReader reader, int ordinal)
    {
        return reader.IsDBNull(ordinal) ? null : (DateTime?)reader.GetDateTime(ordinal);
    }
}

Then call it like so:

ws.Cells[i, 1] = reader.TryGetDateTime(1);

To handle any data type, you could try using generics:

public static T TryGetValue<T>(this DataTableReader reader, int ordinal)
{
    return reader.IsDBNull(ordinal) ? default(T) : reader.GetFieldValue<T>(ordinal);
}

Then call it like this:

ws.Cells[i, 1] = reader.TryGetValue<DateTime?>(1);

Upvotes: 3

wintermute
wintermute

Reputation: 186

Try something like:

ws.Cells[i, 1] = reader.IsDbNull(0) ? null : reader.GetString(0);

Upvotes: 0

DaveShaw
DaveShaw

Reputation: 52808

You can use reader.IsDBNull(int) to check if a field is null before attempting to read a value from it.

For example

ws.Cells[i, 1] = reader.IsDBNull(0) ? "Default value when null" : reader.GetString(0);

Upvotes: 7

Related Questions