如何使用DataTable和For Each Loop填充List?

时间:2013-04-18 10:43:02

标签: sql .net vb.net datatable generic-list

我正在尝试使用DataTable填充List,我为每个循环检查每一行并将该项添加到列表中。但代码不起作用,我不断收到错误..

  

System.NullReferenceException:{“对象引用未设置为   对象的实例。“}

-Data:{System.Collections.ListDictionaryInternal}

-HelpLink:Nothing -Inner Exception:Nothing

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

这是我的代码......

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 个答案:

答案 0 :(得分:5)

目前lUserNames尚未初始化。你需要这样做:

Dim lUserNames As New List(Of String)

答案 1 :(得分:3)

您已声明List,但尚未对其进行初始化。

所以改变

Dim lUserNames As List(Of String) = Nothing

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

当然NullReferenceException如果getDataTable返回Nothing而不是空DataTable,如果tblUsersIf dt.Rows.Count > 0为空,那么您也会获得{{1}} }。

答案 2 :(得分:1)

您没有在第4行初始化您的列表。它应该是:

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

编辑:显然这有点像CSharp'ism :)这也有效:

Dim lUserNames As New List(Of String)