Difference between nothing and system.DBNull - vb.net

I am working in VB.NET and I am wondering about the difference between Nothing and System.DBNull.
When I fire save query at that time I am giving value from grid at runtime like as follow:
gvMain.Rows(j).Cells("Brand").Value.ToString()
But it shows me error when it has value of Nothing and it works perfectlly when it has value of System.DBnull.
What to do in this case?
Thanks in advance

The keyword Nothing is used to specify or asign that a var of reference type is not pointing anything, no object is instanciated for this var.
DBNull.Value, on the other hand, is an object used to point out that a type of a field of the DataBase is of null value.

Nothing is of Type System.Object.
It represents the default value of any data type.
DBNull.Value is of Type System.DBNull
If something shows up as System.DBNull, that means that even though it doesn't have a value, it has a valid pointer. As you may have found out, it cannot be converted to a string, integer, etc. You must do a check (preferably using IsDBNull.
If IsDBNull(gvMain.Rows(j).Cells("Brand").Value) Then
Return String.Empty
Else
Return gvMain.Rows(j).Cells("Brand").Value.ToString().Trim()
End If

Related

VB.Net - Can you access the expected data type within a function?

I was wondering if there is any way to access the expected data type within a function similar to an event arg. I am doubtful that this is possible, though it would be an excellent feature.
I frequently work with (old and disorganized)Mysql databases creating interfaces through VB.Net. Often I will have an optional field which contains a NULL value in the database. I am frequently dealing with errors due to NULL and dbnull values in passing data to and from the database.
To complicate things, I often am dealing with unexpected datatypes. I might have an integer zero, a double zero, an empty string, or a string zero.
So I spend a fair amount of code checking that each entry is of the expected type and or converting NULLs to zeros or empty strings depending on the case. I have written a function ncc(null catch convert) to speed up this process.
Public Function ncc(obj As Object, tp As Type) As Object 'Null Catch Convert Function...
My function works great, but I have to manually set the type every time I call the function. It would be so much easier if it were possible to access the expected type of the expression. Here is an example of what I mean.
Dim table as datatable
adapter.fill(table)
dim strinfo as string
dim intinfo as long
strinfo = ncc(table.Rows(0).Item(0),gettype(String)) 'here a string is expected
intinfo = ncc(table.Rows(0).Item(0),gettype(Long)) 'here a long is expected
It would be so much more efficient if it were possible to access the expected type directly from the function.
Something like this would be great:
Public Function ncc(obj As Object, optional tp As Type = nothing) As Object
If tp Is Nothing Then tp = gettype(ncc.expectedtype)
That way I do not have to hard code the type on each line.
strinfo = ncc(table.Rows(0).Item(0))
You can make the ncc function generic to simplify calling it:
Public Function ncc(Of T)(obj As T) As T
If DbNull.Value.Equals(obj) Then Return Nothing
Return Obj
End Function
This kind of function will be able to in some cases infer the type, but if there's any possibility of null you'll still want to include a type name (because DBNull will be the inferred type for those values). The advantage is not needing to call gettype() and so gaining a small degree of type safety:
strinfo = ncc(Of String)(table.Rows(0).Item(0))
But I think this has a small chance to blow up at run time if your argument is not implicitly convertible to the desired type. What you should be doing is adding functions to accept a full row and return a composed type. These functions can exist as static/shared members of the target type:
Shared Function FromDataRow(IDataRow row) As MyObject
And you call it for each row like this:
Dim record As MyObject = MyObject.FromDataRow(table.Rows(i))
But, you problem still exists.
What happens if the column in the database row is null?
then you DO NOT get a data type!
Worse yet? Assume the data column is null, do you want to return null into that variable anyway?
Why not specify a value FOR WHEN its null.
You can use "gettype" on the passed value, but if the data base column is null, then you can't determine the type, and you right back to having to type out the type you want as the 2nd parameter.
You could however, adopt a nz() function (like in VBA/Access).
So, this might be better:
Public Function ncc(obj As Object, Optional nullv As Object = Nothing) As Object
If obj Is Nothing OrElse IsDBNull(obj) Then
Return nullv
End If
Return obj
End Function
So, I don't care if the database column is null, or a number, for such numbers, I want 0.
So
dim MyInt as integer
Dim MyDouble As Double
MyInt = ncc(rstData.Rows(0).Item("ContactID"), 0)
MyDouble = ncc(rstData.Rows(0).Item("ContactID"), 0)
dim strAddress as string = ""
strAddress = ncc(rstData.Rows(0).Item("Address"), "")
Since in NEAR ALL cases, you need to deal with the null from the DB, then above not only works for all data types, but also gets you on the fly conversion.
I mean, you CAN declare variables such as integer to allow null values.
eg:
dim myIntValue as integer?
But, I not sure above would create more problems than it solves.
So,
You can't get exactly what you want, because a function never has knowledge of how it's going to be used. It's not guaranteed that it will be on the right-hand side of an assignment statement.
If you want to have knowledge of both sides, you either need to be assigning to a custom type (so that you can overload the assignment operator) or you need to use a Sub instead of an assignment.
You could do something like this (untested):
Public Sub Assign(Of T)(ByVal field As Object, ByRef destination As T,
Optional ByVal nullDefault As T = Nothing)
If TypeOf field Is DBNull Then
destination = nullDefault
Else
destination = CType(field, T)
End If
End Sub
I haven't tested this, so I'm not completely certain that the compiler would allow the conversion, but I think it would because field is type Object. Note that this would yield a runtime error if field is not convertible to T.
You could even consider putting on a constraint requiring T to be a value type, though I don't think that would be likely to work because you probably need to handling String which is a reference type (even though it basically acts like a value type).
Because the destination is an argument, you wouldn't ever need to specify the generic type argument, it would be inferred.

Cell ColumnType is NULL using Smartsheet API

I'm trying to update my SmartSheet API from v1 to v2 and am having some difficulty on the code below.
The code returns rows for the selected sheet, however the "ColumnType" property of all the Cell's within the rows are NULL.
I know to return this you have to specify it as an inclusion - which I believe I have.
Dim sheet As Sheet = smartsheet.SheetResources.GetSheet(curSheet.Id, New RowInclusion() {RowInclusion.COLUMN_TYPE, RowInclusion.COLUMNS}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
For Each Row As Row In sheet.Rows
If Row.ParentRowNumber Is Nothing Then
Dim i As Integer = 0
Dim colType As ColumnType
If Not Row.Cells(i).ColumnType = ColumnType.TEXT_NUMBER Then
'Do some stuff here...
End if
Next
Any help would be great.
Thanks,
Steve
The short answer is just get the latest SDK from https://github.com/smartsheet-platform/smartsheet-csharp-sdk/pull/60 and update your GetSheet to the following:
Dim sheet As Sheet = client.SheetResources.GetSheet(SHEETID, New SheetLevelInclusion() {SheetLevelInclusion.COLUMN_TYPE}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
Notice the use of SheetLevelInclusion rather than RowInclusion. You should be all set.
If you care about the details, the longer answer is... The GetSheet method doesn't accept an array/IEnumerable of RowInclusion as the second argument. It expects an array/IEnumerable of SheetLevelExclusion. In C#, the same invocation call would fail as C# imposes stricter type checking on the generic type parameter of IEnumerable. However, due to Visual Basic's leniency around implicit conversions between Enum types and its lenient conversions for arrays (and similar types like IEnumerable) it is possible to invoke a function with the "wrong" type of argument when the argument is an array/IEnumerable and the elements are Enums. In this case, Visual Basic is actually converting the RowInclusion values to their underlying numeric value (Enum is always implicitly or explicitly backed by an underlying numeric type) and converting those values to the SheetLevelExclusion value corresponding to the same underlying numeric value so that it can invoke the GetSheet method.
The other complication here is that the SDK didn't have COLUMN_TYPE as an available SheetLevelExclusion value. So the pull request/branch I linked to above adds that. In my simple test here that made it work.

Why is my Nullable(Of Int32) = 0 after I set it to Nothing?

I think I'm missing something fundamental about nullable types. Hopefully this example will open up new understanding, but at the very least, maybe we can get this one thing working right.
In a Class (a dialog form), I declare:
Property ProductStructureHeaderKey As Int32?
In another Class, I declare an instance of that dialog and attempt to set that Property with this line:
dr.ProductStructureHeaderKey = If(parentRow.Cells(1).Value Is Nothing, Nothing, Int32.Parse(parentRow.Cells(1).Value))
When that line assigns Nothing to the property, the property is equal to 0. (And then later, it's passing 0 to the DB when I want it passing NULL.)
That's not what I expect and I keep finding code (SO, MSDN, etc) that looks like I'm doing things right, but clearly, I'm not. So, friends, what am I doing wrong? How do I employ Nullable types to meet my needs?
That's one of the differences between C# and VB.NET. In VB.NET Nothing does not only mean null but also default. So you are assigning the default value of Int32 to the property what is 0. This is caused by the If-operator that has to infer the type from the two values not from the property that you want to assign.
Instead use either an If...Else:
If parentRow.Cells(1).Value Is Nothing Then
dr.ProductStructureHeaderKey = Nothing ' Now it's not 0 but Nothing
Else
dr.ProductStructureHeaderKey = Int32.Parse(parentRow.Cells(1).Value)
End If
or force the nullable with new Nullable(Of Int32):
dr.ProductStructureHeaderKey = If(parentRow.Cells(1).Value Is Nothing, new Nullable(Of Int32), Int32.Parse(parentRow.Cells(1).Value))
Further read: Why is there a difference in checking null against a value in VB.NET and C#?

Strange behaviour of the If() statement

today I stumbled upon a strange behaviour of the VB.net If() statement. Maybe you can explain why it is working like it does, or maybe you can confirm that it is a bug.
So, I have a SQL database with a table "TestTable" with an int column "NullableColumn" that can contain NULL. I'd like to read out the content of this column.
So I declare a variable of type Nullable(Of Integer) for that matter, open a SqlClient.SqlDataReader for "SELECT NullableColumn FROM TestTable" and use the following code to get the content of this column:
Dim content as Nullable(Of Integer)
...
Using reader as SqlClient.SqlDataReader = ...
content = If(reader.IsDBNull(reader.GetOrdinal("NullableColumn")), Nothing, reader.GetInt32(reader.GetOrdinal("NullableColumn")))
End Using
But after that my variable content has the value 0, not Nothing as I would have expected.
When debugging everything looks alright, so
reader.GetOrdinal("NullableColumn") delivers the correct ordinal position of this column (which is 0)
reader.IsDBNull(0) and reader.IsDBNull(reader.GetOrdinal("NullableColumn")) deliver True, since the content of this column indeed is NULL
If(1=2, Nothing, "Not Nothing") delivers the String "Not Nothing"
If(1=1, Nothing, "Not Nothing") delivers Nothing
reader.GetInt32(reader.GetOrdinal("NullableColumn")) throws an error, since NULL can't be converted to Integer
So, why does my variable has the value 0?
In VB Nothing is not the same as null. The If operator must determine the type of its result based on the arguments passed to it. Nothing, of course, has no type so the only type that the If operator can return in your code is Int32. If the IsDBNull method returns true, then the If operator returns Nothing cast as Int32. In VB, Nothing returns the default value for a type. For an Int32, the default value is 0.
From MSDN on the Nothing keyword:
Nothing represents the default value of a data type. The default value depends
on whether the variable is of a value type or of a reference type.
For non-nullable value types, Nothing in Visual Basic differs from null in C#.
In Visual Basic, if you set a variable of a non-nullable value type to Nothing,
the variable is set to the default value for its declared type. In C#, if you
assign a variable of a non-nullable value type to null, a compile-time error
occurs.
I think just a regular If would work best:
If Not reader.IsDBNull(reader.GetOrdinal("NullableColumn")) Then
content = reader.GetInt32(reader.GetOrdinal("NullableColumn"))
End If
Or to keep it shorter
If Not reader.IsDBNull(reader.GetOrdinal("NullableColumn")) Then content = reader.GetInt32(reader.GetOrdinal("NullableColumn"))
But after that my variable content has the value 0, not Nothing as I would have expected.
How do you check the content value?
First of all, you should start with content.HasValue property. It should be False for your case of Nothing and True when correct value was fetched from database.
You should also get InvalidOperationException while accessing content.Value when it hasn't got value.
Chris has given the explanation but I dislike the style of assignment he’s chosen because it splits assignment from variable declaration.
By contrast, I recommend initialising variables upon declaration. In this case it’s admittedly slightly convoluted since you need cast either operator of If to the correct type first.
Dim content = If(reader.IsDBNull(reader.GetOrdinal("NullableColumn")),
DirectCast(Nothing, Integer?),
reader.GetInt32(reader.GetOrdinal("NullableColumn")))
Actually you can also use the slightly shorter New Integer?() instead of the DirectCast.
Of course now content is declared inside the Using block – this might not be what you want but you should try to make the declaration as local as possible.
Furthermore, this code is complex and will probably be reused. I suggest creating a separate (extension) method to convert database NULL values to nullables:
<Extension> _
Public Shared Function GetNullable(Of T)(SqlClient.SqlDataReader this, String fieldName) As T?
Dim i = this.GetOrdinal(fieldName)
Return If(this.IsDBNull(i), New T?(), this.GetFieldValue(Of T)(i))
End Function
Now you can use it as follows:
Dim content = reader.GetNullable(Of Integer)("NullableColumn")

Why does setting a DataSet row value to Nothing initialize it to the data type minvalue?

When setting a DataSet row column to Nothing, like row.Date = Nothing, why does it initialize it to the data type minvalue? In this case a date, that gets set to 0000-01-01. The column is set to allow null etc., and if I don't set the row to anything at all, it will leave the column empty. So why does Nothing act this way?
In C# I would've set it to DbNull, I guess, but I'm a tad green on VB.NET - as you might be able to tell. :)
Hps is correct that you should use DBNull.Value to assign a NULL value to a database column.
row.Date = DBNull.Value
The reason you see the a default value being set is that the keyword Nothing in VB.NET is comparable to default(T) in C#, not C#'s null keyword.
I think you will be able to set DBNull in VB.Net as well something like
table.Rows(0)(0) = System.DBNull.Value
or row.Date = System.DBNull.Value
For assigning the "Nothing", you will need to have Nullable Type