Shaheer Muhammad Shaheer Muhammad - 2 years ago 75 Question

When nullable integer got null value not executing the command

I have VB.Net code which value taking from db and if it is null do some job

While reader.Read
tocken = reader.GetInt16("Tocken_No")
If tocken.HasValue = False Then
TxtPTocken.Text = 1
TxtPTocken.Text = tocken + 1
End If
End While

Else statement working properly but first part not. tocken is nullable short. What I'm missing? Please help

Answer Source

That code doesn't make sense. You're calling GetInt16, which means you're going to get an Int16. Your tocken variable may be type Nullable(Of Short) but you're assigning a value to it so HasValue is ALWAYS going to be True.

Your issue there is that if your database field is NULL then your code is going to throw an exception. Methods like GetIn16 fail if there isn't a value of the expected type available. It's up to you to check for NULL and handle that accordingly:

tocken = If(reader.IsDBNull(reader.GetOrdinal("Tocken_No")),
            CType(Nothing, Short?),
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download