I am running an SQL Query with data readers in vb.net
reader3 = myCommand3.ExecuteReader
reader3.Read()
If reader3.HasRows Then
FromToDates = reader3.GetString(3)
End If
There are no rows being returned in this particular query, however even though the if reader3.HasRows is being used its still showing an error saying:
Additional information: Data is Null. This method or property cannot be called on Null values.
this is when trying to set the FromToDates variable but there are no rows being returned so it should not even reach this part
I doubt that there are no rows, i assume that there is at least one row where the value is NULL. You could check it with the IsDBNull-method:
If reader3.HasRows AndAlso Not reader3.IsDbNull(3) Then
FromToDates = reader3.GetString(3)
End If
However, the variable name suggests that it's a date, but you are storing it as string. Use the correct type which is date or datetime. If it's actually a datetime use:
Dim FromToDates As Date
If reader3.HasRows AndAlso Not reader3.IsDbNull(3) Then
FromToDates = reader3.GetDateTime(3)
End If
if you are using Reader.read() then i don't think so you need reader,hasrow(). you can do somthing like this
reader3 = myCommand3.ExecuteReader
If reader3.Read()Then
FromToDates = reader3.GetString(3)
End If
and related to your error its look like you are getting NULL value from database and in vb you can not read NULL, i will suggest to use ISNULL(Column_NAME,'') function in your SQL Script.
It seems that even though the row is empty (all DBNull, perhaps), there IS a row object returning from the query. There are several different solutions presented in this thread that all take differing approaches to catching the empty row before it errors!
http://www.vbforums.com/showthread.php?555183-datareader-and-empty-records
Related
I have added dummy data to my SQL database.
When I try to run the VB it comes back with a null error.
What I have done is delete the dummy data from the database so it not reading the null value anymore.
Even after deleting it the VB file is still throwing the error like the null values are still there.
I have run a sql script to check and I can confirm it not longer there.
Here is the line of code that throwing the error.
If Date.Now.AddDays(LoadsFilter * -1) > Convert.ToDateTime(myReader(2)) Then
ShowLoad = 0
End If
I'm still quite new to vb so I'm not sure what to do here.
I was thinking of passing a method to read null values but I have already deleted the null value. I'm not sure how to go about this, can anyone help please?
There's no need for any conversion. The data reader has its own methods for null tests and for getting data in the appropriate type, e.g.
If Not myDataReader.IsDBNull(2) Then
Dim dt = myDataReader.GetDateTime(2)
'Use dt here.
End If
You can also use a single line to get a Nullable(Of Date):
Dim dt = If(myDataReader.IsDBNull(2), New Date?, myDataReader.GetDateTime(2))
Note that, if you prefer to use column names rather than indexes, which make your code clearer, then you can use the GetOrdinal method, as those other methods only support indexes:
Dim dt = If(myDataReader.IsDBNull(myDataReader.GetOrdinal("ColumnName")),
New Date?,
myDataReader.GetDateTime(myDataReader.GetOrdinal("ColumnName")))
I have the following code:
Try
Dim queryString As String
queryString = "Insert into ServiceRecords([Personnel]) Values(#Personnels)"
command1 = New OleDbCommand(queryString, connection)
For i As Integer = 0 To Me.ListBox1.Items.Count + 1
command1.Parameters.AddWithValue("Personnels", ListBox1.Items(i))
command1.Parameters.Clear()
command1.ExecuteNonQuery()
Next
Catch ex As Exception
End Try
But I get the error below, and I don't know how to fix it. I think it happens because of my code.
And this is what I get:
Let's review.
First, as muffi suggested, use the Add method instead of .AddWithValue but instead of DBType use OLEDBType. There is not .String type in OleDBType. You will have to check your Access db to get the correct datatype. Probably VarChar. In addition, the parameter name should match the parameter name in your query string. With Access the position is the important thing but with other databases the name matters.
Second, as Charles suggested, change the plus one to minus 1. Most people start counting at one but computers usually start at zero so the upper index of the ListBox is one less than the Count (remember you are starting at zero not one).
Third , as Charles also pointed out it is wrong to clear the parameters before you execute. Then you would have nothing in your parameter. It is not necessary to clear them at all because you are overwriting the Value property with each iteration of your loop and I have set the name and datatype outside the loop because they stay the same. We don't want to reset properties for each iteration when they don't change.
command1.Parameters.Add("#Personnels", OleDbType.VarChar)
For i As Integer = 0 To ListBox1.Count -1
command1.Parameters("#Personnels").Value = ListBox1.Items(i)
command1.ExecuteNonQuery
Next
I am not vb.net expert, but made to work on it for now.
Retrieving value for database, which in some cases Is NULL for a datetime column (Sql database).
When it is retrieved in vb.net using something like this.
select testcolumn from testtable
and result converted to datatable.
the value fails validation(even though the retrieved value in database is null)
If Not dt("testcolumn") Is Nothing
End If
Ideally this validation is point for me which decides whether the value should be assigned to a property for class. but as this fails.next exception I get is Invalid cast, as i try to do something Like
myClass.datetimeProperty=dt("testcolumn").ToString()
Any reason for this, and is only way to perform additional validation of
If Not string.isnullOrEmpty(dt("testcolumn)
Instead of checking on Nothing, you have to check on DBNull.Value.
If dt("testcolumn") IsNot DbNull.Value
'your code
End If
Or another alternative:
If NOT IsDbNull(dt("testcolumn")) Then
'your code
End If
I've been trying so hard to find a solution for this, but no luck. I'm fairly new to VB and SQL, but this shouldn't be too hard. I've inherited a lot of code and there's not too much room to change db attribute types or anything.
I'm trying to run an UPDATE query using parameters in Razor, like so:
Dim updateCommand = "UPDATE [tblJobRating] SET [ProjectManagement] = #0, [ProjComments] = #1, [Schedule] = #2, [SchedComments] = #3 WHERE [JobRatingID] = #4"
All of the columns in question need INT values, but I have one exception where I need to pass it a null value (passing another number or zero won't do). Essentially a "N/A" value for the user.
I assign the variables from Post requests, like so:
Dim projMgmt = Request.Form('projMgmt')
' ...
Dim sched = Request.Form('sched')
I have the "N/A" value posting no value right now (or it can be a string and I can check for IsNumber if need be, I guess). But when I call the query execution, it enters the value as a 0.
db.Execute(updateCommand, projMgmt, projComments, sched, schedComments, ratingId)
It needs to be a NULL value for the backend to work properly. I've tried type checking and passing Nothing, System.Data.SqlTypes.SqlInt32.Null, etc., but it either gives conversion errors or sets to 0. How can I pass it properly?
Edit: I left out the first param in the db.Execute method, passing in the updateCommand. Edited for clarity.
The problem is in your vb variable definition. I assume you have an integer, it needs to be a nullable(of integer) all the way through to the SQL. This can also be written as integer?.
I have:
Dim nVar1 As Long?
Dim nVar2 As Long?
Dim nVarSum As Long?
nVar1 = Nothing
nVar2 = 5
nVarSum = nVar1 + nVar2
I would prefer the result to end with nVarSum being 5, instead of Nothing.
I understand if you add something to an unknown value, you will end up with "somthing + unknown" or
x+5 will always equal "x+5" not "5" because you are still carrying around that unknown "x".
However, how can I effectively treat an unknown or Nothing as a zero for the purposes of addition in this case?
Thanks!
(What is basically happening is that the end user is sending us a data file, this code parses that file and then sums together about 15 fields. If the user leaves those fields blank instead of assigning a zero to them, I need to treat it as if it was a zero for this one addition operation, but all the rest of the code needs to continue seeing it as a Nothing value since the user did not ACTUALLY submit zero... they submitted blank or nothing)
nVar1.GetValueOrDefault()+ nVar2.GetValueOrDefault()
Or in c#:
(nVar1??0)+(nVar2??0)
I think the simplest way is to use the If operator to coerce Nothing values into a default one.
nVarSum = If(nVar1,0) + If(nVar2,0)
The If operator in the 2 argument form when applied to nullable types essentially does the following. If the nullable has a value then the return is the value, otherwise it's the second argument.
Or explicitly test for nothing and set your default value. Same result as other answers posted.
If nVar1 is nothing then
nVar1 = 0
end if
nVarSum = nVar1 + nVar2