简体   繁体   中英

Handling VB.NET DataRow Input string was not in a correct format for a null value

I am looping through the rows of a DataRowCollection and assigning the fields of each row to a variable. I always get "Input string was not in a correct format" no matter how I cast this. I just need gapCd to contain 0 if the field is null or the value otherwise. It seems the IsDbNull is not returning true properly. I've also tried DbNull.Value comparisons with no luck. Any help is much appreciated.

Dim gapCd As Integer = IIf(IsDBNull(row("GAP_CD")), 0, row("GAP_CD"))

Remember that as a value type, Integer is already initialized to zero. So try this:

Dim gapCd As Integer 
If Not IsDBNull(row("GAP_CD")) Then gapCd = CInt(row("GAP_CD")) 

and if that doesn't work, it's time to try some logging:

Dim gapCd As Integer
Try
    If Not IsDBNull(row("GAP_CD")) Then gapCd = CInt(row("GAP_CD"))
Catch Ex As Exception
    SomeLoggingFunction(row("GAP_CD").ToString())
End Try 

Saw this again today for some reason, and on the fresh read was clear to me that all you have to do is remove one "I" from your code to change the IIf() function to the If() operator and force short-circuiting evalutation:

Dim gapCd As Integer = If(IsDBNull(row("GAP_CD")), 0, row("GAP_CD"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM