VB.net if block throwing an error - vb.net

My code block is below. As it turns out, rdrCurrentRate.GetString(12) is a null value, but the code block throws an error. "Data is Null. This method or property cannot be called on Null values."
My intention is to write "if rdrCurrentRate.GetString(12) is NOT NULL, then sCurrentRateType = rdrCurrentRate.GetString(12)"
What am I missing here?
If Not String.IsNullOrEmpty(rdrCurrentRate.GetString(12)) Then
sCurrentRateType = rdrCurrentRate.GetString(12)
End If

You probably want to use the IsDBNull method instead:
If Not rdrCurrentRate.IsDBNull(12) Then
sCurrentRateType = rdrCurrentRate.GetString(12)
End If
Null values are not represented by null in the data reader, but instead of a special DBNull value. The IsDBNull method will check if the column represents such a value.

Try this:
If IsDBNull(rdrCurrentRate.GetString(12))=false Then
sCurrentRateType = rdrCurrentRate.GetString(12)
End If
Hope this works.

I'm thinking about 2 possibilities
1- An exception is raised in the rdrCurrentRate.GetString
2- rdrCurrentRate.GetString returns a DBNull value, which is not the same as Nothing (or null)

Related

Conditional Statement Returns Exception Error

I have this conditional statement
loRecordFieldData = CType(IIf(loRecordsAttributeCollection.ContainsKey(loMappingObject.FieldID), _
loRecordsAttributeCollection(loMappingObject.FieldID), Nothing)
the problem is when loRecordsAttributeCollection doesn't contain the FieldID it return exception error key not found instead of nothing.
Could anyone explain this and how to prevent it?
Thank you
IIf is a function, so all of its arguments will be evaluated before it’s called. Use If instead, which is a genuine inline conditional and won’t evaluate the operand that isn’t returned:
loRecordFieldData = CType(If(loRecordsAttributeCollection.ContainsKey(loMappingObject.FieldID), _
loRecordsAttributeCollection(loMappingObject.FieldID), Nothing)
If this is a dictionary, you can also use TryGetValue or wrap it in an extension method:
Dim loRecordFieldData As … ' the value type of loRecordsAttributeCollection
loRecordsAttributeCollection.TryGetValue(loMappingObject.FieldID, loRecordFieldData)
' now cast
Use If instead. IIf syntax is obsolete in vb.net

Assign null value to data row

I am trying to write one line IF condition when assign value to property.
I've tried these syntax in VB.NET, type_of_documents is nullable integer:
1) vehicle.type_of_documents = If(vehicle.Istype_of_documentsNull, SqlTypes.SqlInt32.Null, vehicle.type_of_documents)
2) vehicle.type_of_documents = If(vehicle.Istype_of_documentsNull, DBNull.Value, vehicle.type_of_documents)
3) vehicle.type_of_documents = If(vehicle.Istype_of_documentsNull, Nothing, vehicle.type_of_documents)
Well, I am a little pushy to do this in one line. Somehow, all these syntax have failed to assign null value to my database. Syntax 1 & 2 have thrown cast integer exception. Syntax 3 is no error but no change/update value in database (same as previous).
Can anyone show me better syntax? Since I am really not into VB.NET.
Thanks in advance
The If operator is basically generic, i.e. the type it returns is inferred from the type of the second and third arguments. That means that those two arguments have to be the same type or one must assignable from the type of the other. A simple cast is all you need:
vehicle.type_of_documents = If(vehicle.Istype_of_documentsNull,
CObj(DBNull.Value),
vehicle.type_of_documents)
Now that the first argument is specified to be type Object, the two arguments share a type.
Return type of If method will be inferred from result parameters (as #jmcilhinney already answered).
In 1 and 2 samples you get cast exception because Integer cannot be casted to SqlTypes.SqlInt32.Null and DbNull.Value types.
Third sample compile because Nothing can be introduced as Integer, it simply default value of Integer which equals 0.
If you want return DbNull.Value in case when type_of_documents has no value - you need cast results in their common type, which is Object.
Instead of If method you can create extension method which return common type(object) required by SqlParameters
Public Module Extensions
<Extension>
Public Function GetValueOrDbNull(this As Integer?) As Object
If this.HasValue Then Return this
Return DBNull.Value
End Function
End Module
And use it
Dim sqlValue = vehicle.type_of_documents.GetValueOrDbNull()

Setting a variable to null value in inline if statement

I'm trying to use the following code to check for a DBNull and set the variable to nothing if it is, or a short if it isn't. The problem is it is failing to set the variable to Nothing and sets it to a 0 instead. Anybody know why?
variable = If(currentRow.Item("variable") Is DBNull.Value,
Nothing, CShort(currentRow.Item("variable")))
If variable is declared As Short? then the code works with a slight tweak: you need to cast either operand of If to the target type first:
variable = If(condition, CType(Nothing, Short?), CShort(…))
(You could also have cast the third operand instead, or both.)
This cast is necessary because of how If deduces types: if the two result types mismatch, a common type is deduced which is the closest parent type, i.e. a type from which both inherit. However, with Nothing, new rules come into play because as far as VB is concerned, Nothing is already a valid Short – a default-initialised one (see old answer below for explanation). So VB doesn’t try any type coercion, it simply uses Short as the return value.
Old answer below, assuming that OP had declared variable As Short:
You cannot set value types to Nothing. If you assign Nothing to a value type then it will be set to its type’s default value instead – which is 0 for Short.
You can test this easily:
Dim s as Short = Nothing
Console.WriteLine(s)
Setting a value type to Nothing is the same as invoking its default constructor (New Short()) or declaring a new variable of that type without initialising it. The corresponding operation in C# would be to assign default(T) (short s = default(short)).
If you want to represent null value types, you have to use nullable types:
Dim s as Short? = Nothing
Now s is of type Nullable<Short> (Short? is a shortcut of that) and can be assigned a proper Nothing.

Why does this code NOT create a Visual Studio warning about not returning a value on all code paths? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
No warning in VB.NET when function has no return
While writing the following function, I noticed that I was NOT getting a warning about not returning a value on all code paths. The CASE ELSE clause is not returning a value, so it should be giving me a warning. I tried changing the notification level from Warning to Error, but it's still not complaining about it.
Public Function LookupOccasionGroup(ByVal occasion As GCOccasionType) As GCOccasionGroups
Dim occasionInfo = _occasionTypes.FindByOccasionTypeID(occasion)
If occasionInfo Is Nothing Then
Throw New InvalidOperationException("blah blah")
End If
Select Case occasionInfo.OccasionGroupID
Case GCOccasionGroups.DineIn, GCOccasionGroups.Delivery, GCOccasionGroups.CarryOut
Return CType(occasionInfo.OccasionGroupID, GCOccasionGroups)
Case Else
Log.Warn("Blah Blah.")
End Select
End Function
You are confusing VB.NET with a different language; not assigning the return value is permitted in VB.NET. The return value is Nothing, same thing as default(T) in C#. This has always been permitted in Visual Basic.
The screenshot shows a different diagnostic, the one you get when you forget to declare the function return value type. The compiler can now no longer figure out reliably what to return when no assignment is made. It punts for Object and returns Nothing when no assignment was made. That's very likely to blow up with an inscrutable NRE exception, thrown at a location that leaves little hint where the true problem is located:
Function Foo()
End Function
You'll now get:
error BC42021: Function without an 'As' clause; return type of Object assumed.
error BC31072: Warning treated as error : Function without an 'As' clause; return type of Object assumed.
error BC42105: Function 'foo' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
The first two errors are generated by the "Implicit type; object assumed" condition in that same list. The third error is the one you are looking for, and the warning turned into an error by the change. You don't actually want to use this of course.
Are all the possible values of the enum contained within the first case? If so, then it is conceivable that there's enough intelligence there to believe the else will never be hit.
To test this, either add a new value to the enum, or remove one of the possible values from the first case.

How do you assign null value to optional parameters in VB.NET 1.1

I tried DbNull.Value but no luck. How do I assign a default value as null to a string parameter that is null in VB.NET? Its litte strange to see that VB does not have anything like plain null as most of the other languages do. Also what is the difference between null and DbNull and Nothing. Thanks Guys.
Nothing is what you use in VB for null, so VB has no null, and DBNull is to be used to pass null to database when, for example, you are constructing a call to stored procedure and one of its input parameters needs to be null.
VB.Net's closest equivalent to null is Nothing.
Note that this isn't a direct analog to C#'s null, but rather a closer match for C#'s default(T). However, it should do what you need here.
use nothing instead of null