1

I am working on a new ASP.Net 4.0 data driven app. In the DAL I check for NULL values on all my data and default to the proper data when NULL. I have a strange issue going on. Two dates are coming back - on one I need the time only. The First line of code for the full date works without fail - but the second line of code errors pointing to the format string but the strange part is that it errors on NULL values which does not use the format string and just returns Date.MinValue. When the second line gets data it formats the return correctly.

Dim dr As DataRow
.TourDate = IIf(dr.IsNull("tourdate"), Date.MinValue, Format(dr("tourdate"), "MM/dd/yyyy"))

.TourTime = IIf(dr.IsNull("tourtime"), Date.MinValue, Format(dr("tourtime"), "T"))

The error comes on the second line when dr("tourtime") is NULL - the erroe is: Argument 'Expression' is not a valid value.

Jim Evans
  • 6,285
  • 10
  • 37
  • 60

3 Answers3

6

IIf in VB.Net does not do short-circuit evaluation, so the Format call is being executed even if the value is null.

You need to use If:

.TourTime = If(dr.IsNull("tourtime"), Date.MinValue, Format(dr("tourtime"), "T"))

This is the same issue described here: Using VB.NET IIF I get NullReferenceException

Community
  • 1
  • 1
Sean Carpenter
  • 7,681
  • 3
  • 37
  • 38
  • Damn those quirky evaluations....good job on the definition of `short-circuit` with `IIF`. Been using it and had never thought that it did a full evaluation before rendering. – GoldBishop May 31 '17 at 13:28
0

To trouble-shoot this, I would inspect the actual value stored. A datetime column that appears to be null may actually have a value.

-1

I think you should use IsDbNull instead of IsNull.

Anuraj
  • 18,859
  • 7
  • 53
  • 79
  • 2
    `IsNull()` checks for `DBNull.Value` already, this should not be the issue. – JonH Apr 14 '11 at 16:53
  • @JonH is correct. And DataRow does not have a IsDBNull method but it does have a IsNull method. – Jim Evans Apr 14 '11 at 16:57
  • @Jim Evans - what exactly is `.TourTime` you try to store a min date or a time in there, apparently it doesnt like that if there isn't a value so it doesnt like a date. But if there is a value it stores the time. So what is `.TourTime` what is the type of it? – JonH Apr 14 '11 at 17:01
  • @JohnH - Both tourdate and tourtime are Date types in the class and in the database – Jim Evans Apr 14 '11 at 18:16
  • @Jim Evans - Use `If` not `IIF` per the answer given by @Sean Carpenter. – JonH Apr 18 '11 at 17:33