Kayot Kayot - 21 days ago 6
Vb.net Question

Option Strict On and DBNull.Value

I've started converting an application of mine to use Option Strict On. I've been doing the CStr,Ctype etc, and it's been going well.

SQLCommand.Parameters.AddWithValue("@TERMINATE", If(IsNothing(txtEarningsTerminated.DateValue), DBNull.Value, txtEarningsTerminated.DateValue))


Then I hit this. The txtEarningsTerminated.DateValue is a custom masked text box. When it's value is Nothing I don't want to store anything in the database. However, it states

Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed.


When I change DBNull.Value to "" or nothing, the error goes away. However as Nothing, it fails during runtime stating

The parameterized query '(@CONTROL int,@CLIENTCODE nvarchar(10),@NoBill int,@TERMINATE nv' expects the parameter '@TERMINATE', which was not supplied.


I want to put a NULL in the database. This value can be a date and then become a NULL.

How do I translate this so as to not produce an error under Option Strict On?

Answer

So the answer was obvious and in the error. I just had to encase the DBNull.Value in a Ctype Object

CType(DBNull.Value, Object)

And then the code would compile just fine.

Comments