0
votes

I'm trying to populate a List using a DataTable, I have a for each loop that checks every row and adds the item to the list. But the code isn't working, I keep getting the error..

System.NullReferenceException: {"Object reference not set to an instance of an object."}

-Data: {System.Collections.ListDictionaryInternal}

-HelpLink: Nothing -Inner Exception: Nothing

-TargetSite: {System.Collections.Generic.List`1[System.String] getListOfUsers()}

This is my code...

Function getListOfUsers() As List(Of String)

    'Dim i As Integer = 0
    Dim lUserNames As List(Of String) = Nothing

    Dim dt As DataTable = getDataTable(db_Config, "SELECT * FROM tblUsers")

    If dt.Rows.Count > 0 Then

        Try

            For Each dRowItem As DataRow In dt.Rows

                'i = i + 1

                'If IsDBNull(dt.Rows(0)("fldUserName").ToString) = False Then
                '    lUserNames.Add(dt.Rows(0)("fldUserName").ToString)
                'End If

                If dRowItem.Item("fldUserName").ToString <> "" Then
                    lUserNames.Add(dRowItem.Item("fldUserName").ToString)
                End If

            Next dRowItem

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

    End If

    Return lUserNames

End Function
3
Why have you tagged this with C# as well? - Arran

3 Answers

5
votes

Currently lUserNames has not been initialized. You need to do this:

Dim lUserNames As New List(Of String)
3
votes

You have declared the List, but you haven't initialized it.

So change

Dim lUserNames As List(Of String) = Nothing

to

Dim lUserNames As List(Of String) = New List(Of String)

Of course you would also get a NullReferenceException if getDataTable returns Nothing instead of an empty DataTable if tblUsers would be empty at If dt.Rows.Count > 0.

1
votes

You're not initializing your List on line 4. It should be:

Dim lUserNames As List(Of String) = New List(Of String)()

Edit: apparently this is a bit of a CSharp'ism :) This also works:

Dim lUserNames As New List(Of String)