0

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

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

-数据:{System.Collections.ListDictionaryInternal}

-HelpLink:无 -内部异常:无

-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
4

3 回答 3

5

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

Dim lUserNames As New List(Of String)
于 2013-04-18T10:45:01.290 回答
3

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

所以改变

Dim lUserNames As List(Of String) = Nothing

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

当然你也会得到一个NullReferenceExceptionifgetDataTable返回Nothing而不是一个空的DataTableiftblUsers将是空的 at If dt.Rows.Count > 0

于 2013-04-18T10:47:51.397 回答
1

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

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

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

Dim lUserNames As New List(Of String)
于 2013-04-18T10:49:37.190 回答