IIf Function and nulls

  • Thread starter Thread starter Michael
  • Start date Start date
M

Michael

Hello,

I'm trying to assign a date value from a DataSet to a textbox. I'd like to
use the IIf function so the code to assign it would just be one line, and
not multiple lines ( I do have many dates to assign).

So here is my problem, using IIf, I get a lovely error with the following
code

Cast from type 'DBNull' to type 'Date' is not valid.
txtDate.Text = IIf(wcDS.WorkersCompensation(0).Isemployee_dobNull,
String.Empty, CStr(wcDS.WorkersCompensation(0).employee_dob))

But when I create the actual if/else construct it works fine.

If wcDS.WorkersCompensation(0).Isemployee_dobNull Then

txtDate.Text = String.Empty

Else

txtDate.Text = CStr((wcDS.WorkersCompensation(0).employee_dob))

End If

It's almost like for the IIf to work, both the truepart and falsepart would
need to be able to work, all the time, is that so? Anyone have any ideas on
this, or a better way to do it?

Thanks, Michael
 
This is because all 3 parameters to IIF get evaluated regardless of whether
the condition was true or false. It is a function, not a language construct.
And just like with any function, all the arguments get evaluated before the
function runs.

This means that even when it is null, the 3rd argument gets evaluated. When
this happens, you get an error.
 
Michael said:
Hello,

I'm trying to assign a date value from a DataSet to a textbox. I'd like to
use the IIf function so the code to assign it would just be one line, and
not multiple lines ( I do have many dates to assign).

So here is my problem, using IIf, I get a lovely error with the following
code

Cast from type 'DBNull' to type 'Date' is not valid.
txtDate.Text = IIf(wcDS.WorkersCompensation(0).Isemployee_dobNull,
String.Empty, CStr(wcDS.WorkersCompensation(0).employee_dob))

But when I create the actual if/else construct it works fine.

If wcDS.WorkersCompensation(0).Isemployee_dobNull Then

txtDate.Text = String.Empty

Else

txtDate.Text = CStr((wcDS.WorkersCompensation(0).employee_dob))

End If

If wcDS.WorkersCompensation(0).IsEmployee_dobNull Then txtDate.Text =
String.Empty Else txtDate.Text = CStr(wcDS.WorkersCompensation(0).employee_dob)

For a long one liner :)

Mythran
 
Back
Top