views:

140

answers:

3

Some tables I am dealing with have null values and are throwing errors. So far ive tried a few solutions to deal with the nulls with no success.

Here are the code samples from my efforts so far;

If (r("datemodified").Equals(DBNull.Value)) Then
                datemodified = String.Empty
            Else
                datemodified = (r("datemodified"))
            End If

and;

If r.HasRows Then
                datemodified = (r("datemodified"))
            Else
                datemodified = String.Empty
            End If

and;

 If r("datemodified") = Nothing Then
                datemodified = String.Empty
            Else
                datemodified = (r("datemodified"))
            End If

and;

If r.IsDBNull("datemodified") Then
                datemodified = String.Empty
            Else
                datemodified = (r("datemodified"))

and via sql;

Select isnull(datemodified, '')

The end result is an IndexOutOfRangeException.

here is the sql;

select datemodified, maintainedby, email, hitcount from grouping where id = @footid

ps, i have ran the query and it is working ok (i.e all the cols exist)

+4  A: 

To handle the null value in the code you can use the IsDBNull method:

Dim index As Integer = r.GetOrdinal("datemodified")
If r.IsDBNull(index) Then
   datemodified = String.Empty
Else
   datemodified = r(index)
End If

To handle the null value in the SQL you have to give the field a name, to be able to access it by name in the data reader:

select datemodified = isnull(datemodified, '')
Guffa
THanks for the assistance. After trying both of these methods, the problem is still occuring.
Phil
Then the problem is somewhere else... Do you call Read before trying to get data from the data reader? Check the value of r.FieldCount to see if you actually have any columns in the result, and r.GetOrdinal("datemodified") to see if the field is one of them.
Guffa
Thanks Guffa, Its now working. Thanks a lot for the help!
Phil
+2  A: 

The IndexOutofRangeException is becoz of the Column you are trying to access does not exists in the result set.

When you are accessing the Ordinal, or the Column via SqlDataReader, you must specify the Column Index, or the Column Name. In your scenario, you need to specify an Alias for the SQL Column returning.

SELECT ISNULL(datemodified, '') AS [datemodified]
Kosala Nuwan
Thanks for the help. After editing i have; select ISNULL(datemodified, '') AS datemodified, maintainedby, email, hitcount from grouping where id = @footid . Unfortunately the exception is still happening.
Phil