开发者

"System.NullReferenceException" when trying to fill array

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 fi开发者_开发问答ll 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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜