IIF Function

  • Thread starter Sparky Arbuckle
  • Start date
S

Sparky Arbuckle

I am using the IIF function in my application to create an instance and
value of a field if it doesn't exist in the query. I am using a
datagrid to display 4-5 items at a time and if one of the items doesn't
have a revision listed in tblRevisions then the whole page errors out.
I am using the following to try and fix the problem:

Dim intADCN As Integer =
IIf(ds1.Tables("DataTable").Rows(0)("RevNumber") Is Nothing, 0,
ds.Tables("DataTable").Rows(0)("RevNumber"))

I am getting an error: Cast from type 'DBNull' to type 'Integer' is not
valid. It seems as though instead of creating the instance and value of
0, it is simply creating the instance of there being an a row there and
the value is null.

Am I missing something or does anyone have any suggestions?
 
C

Chris Botha

Taken from your example, this will return 0 if the value is Null, else the
value:
Dim intADCN As Integer = "0" & ds1.Tables("DataTable").Rows(0)("RevNumber")
 
S

Sparky Arbuckle

I fixed it!

Dim intRevNumber As Integer

If ds.Tables("DataTable").Rows(0)("RevNumber") Is DBNull.Value Then
intRevNumber = 0
Else
intRevNumber = ds.Tables("DataTable").Rows(0)("RevNumber")
End If
 
K

Kevin Spencer

Dim intADCN As Integer = "0" &
ds1.Tables("DataTable").Rows(0)("RevNumber")

Turning Option Strict Off is extremely bad practice, and the above code is a
horrible example of why. You're treating BOTH a string and possibly Nothing
as an Integer. You're also occasionally concatenating Nothing to a String.
This sort of coding can lead to all kinds of debugging headaches, as well as
not throwing exceptions that should be thrown, thus enabling your app to
pass the smell test in testing, and fail behind your back in production.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Neither a follower nor a lender be.
 
C

Chris Botha

I've been doing this since the days of VB6 and ADO, no problems yet.
Thanks for the comments though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top