tags:

views:

166

answers:

3

This is my code:

Public UserBookings() As String

    If dr.Read() Then
        Dim intCounter As Integer
        intCounter = 0
        While dr.Read()
            UserBookings(intCounter) = dr(0)
            intCounter = intCounter + 1
        End While
        Return UserBookings
    Else
        Return False
    End If

But I get this error at runtime:

A first chance exception of type 'System.NullReferenceException' occurred in Project.exe

And the array doesn't even seem to fill up.

Anything I can do to fix this? Bear in mind it is a dynamic array (I'm not sure how many entries it will have) so I don't see how I can loop through every entry and give it an initial value.

Thanks.

A: 

It seems as though you dr(0) is an empty object, but try adding .ToString() to the end of it. But of course it depends on what datatype UserBookings() is.

Upon speaking with my colleague

you should probably use dr.HasRows instead of "if dr.read()" because you are losing an entire row.

Eric
A: 

Among the problems listed as possible answers here, I also see that you are returning False at one point when return type of the method is string. That is not allowed. You can return Nothing or String.Empty, but not False.

Nick
Thanks for VB.NET's automatic type conversion, this may compile without so much as a warning depending on the project compilation settings.
Jon Seigel
A: 

The easiest option here is to realize that you can use an alternative construct such as an ArrayList (or better, a List(of String))

This way, the object will dynamically grow until you've loaded all the items, and you can return the result as an array

Two possible options below (the generic List(Of x) is preferred.

  Function ReadArray(ByVal dr As IDataReader) As String()
    Dim tempstorage As New List(Of String)
    While dr.Read()
      tempstorage.Add(dr(0))
    End While

    Return tempstorage.ToArray()
  End Function

--

  Function ReadArray2(ByVal dr As IDataReader) As String()
    Dim tempstorage As New ArrayList()
    While dr.Read()
      tempstorage.Add(dr(0))
    End While

    Return tempstorage.ToArray(GetType(String))
  End Function

--

Note: I've added some additional code (assuming that dr is a DataReader, and that you're calling this as a function

Steven_W