I have got this code below:
Dim lJobName As String = \"\"
SQLCommand.CommandText = \"Select JobName from Jobs where Id = @Id \"
SQLCommand.Parameters.Add(New
I try to avoid comparing a string to Nothing, even though it does work in VB.
The Visual Basic .NET runtime evaluates Nothing as an empty string; that is, "". The .NET Framework, however, does not, and will throw an exception whenever an attempt is made to perform a string operation on Nothing.
Plus pseudocoder's answer wont work as currently shown (oJobname is never set to anything)
Dim lJobName as String = String.Empty
Dim oJobName as object = SqlCommand.ExecuteScalar()
If oJobName Is Nothing Then
'Do something with the error condition
Else
lJobName = oJobName.ToString
End If
I think it is possible to handle this situation in the statement of the query:
SELECT ISNULL(FieldID,"0") FROM TableName
and subsequently in the program validate the result:
if then ...... else ...... endif
Whatever the manual says, comparing to Nothing does not work. So If lJobName Is Nothing
will NOT be triggered when the result set is empty.
Comparing to DBNull.Value DID work for me:
If lJobName Is DBNull.Value Then
'Do something with the error condition
Else
'Do something with lJobName which contains a valid result.
End If
It is worth noting that when the result set is empty (i.e. no records were found), this is not an "error".
ExecuteScalar() returns Nothing
if there is an empty result set, which should be preserved when assigning into a string, so I would try this:
Dim lJobName as String = String.Empty
lJobName = SqlCommand.ExecuteScalar()
If lJobName Is Nothing Then
'Do something with the error condition
Else
'Do something with lJobName which contains a valid result.
End If
Of course this doesn't help you if you cause a SqlException, but it should handle the problem of no rows found in the result set.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx