你调用的对象是空的。对于循环

时间:2013-05-08 22:38:04

标签: vb.net

Function FindUserByCriteria(ByVal _state As String, ByVal _county As String, ByVal _status As String, ByVal _client As String, ByVal _department As String, ByVal _ordernumber As String) As DataTable
    'Code to load user criteria from database
    Dim ordertype As String
    If _status = "Online" Then
        ordertype = "Online"
    ElseIf _status = "Tax Cert Call" Then
        ordertype = "Call"
    End If



    Dim TaxConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ConfigurationManager.AppSettings("Database")
    Dim dbConnection As OleDbConnection = New OleDbConnection(TaxConnStr)
    Try

        Dim queryString As String

        queryString = "Select Username, Amount, Rank FROM UserCriteria "
        queryString += "WHERE UserCriteria.State = '" & _state & "' AND UserCriteria.County = '" & _county & "' AND UserCriteria.Status = '" & _status & "' AND UserCriteria.Client = '" & _client & "' AND UserCriteria.Department = '" & _department & "' AND UserCriteria.OrderNumber = '" & _ordernumber & "';"


        Dim dbCommand As OleDbCommand = New OleDbCommand
        dbCommand.CommandText = queryString
        dbCommand.Connection = dbConnection
        Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter
        dataAdapter.SelectCommand = dbCommand
        Dim dataSet As DataSet = New DataSet
        dataAdapter.Fill(dataSet)


        If dataSet.Tables(0).Rows.Count >= 1 Then
            FindUserByCriteria = dataSet.Tables(0)
        End If


        Console.WriteLine(vbCrLf)
        For i = 0 To FindUserByCriteria.Rows.Count - 1
            If Not IsUserOnline(FindUserByCriteria.Rows(i).Item("UserName")) Then
                FindUserByCriteria.Rows(i).Delete()
            End If
        Next
        FindUserByCriteria.AcceptChanges()


    Catch ex As Exception
        Console.WriteLine(ex.Message)
        myLogger.Log(ex.Message)
        SendMail(ex.Message)
    Finally
        dbConnection.Close()
    End Try

End Function

所以,我得到“对象引用未设置为对象的实例”。

的错误
For i = 0 To FindUserByCriteria.Rows.Count - 1

线。我发誓,这不仅仅是3天前为我工作...不知道我的代码最近发生了什么变化,以便弹出这个错误。你能帮忙的话,我会很高兴。

1 个答案:

答案 0 :(得分:0)

你需要反转for循环

 For i = FindUserByCriteria.Rows.Count - 1 to 0 step -1

您需要向后删除,否则您将到达已删除的索引

或者你只需​​要在if if get set中使用任何FindUserByCriteria

    If dataSet.Tables(0).Rows.Count >= 1 Then
        FindUserByCriteria = dataSet.Tables(0)


        Console.WriteLine(vbCrLf)
        For i = 0 To FindUserByCriteria.Rows.Count - 1
            If Not IsUserOnline(FindUserByCriteria.Rows(i).Item("UserName")) Then
                FindUserByCriteria.Rows(i).Delete()
            End If
        Next
        FindUserByCriteria.AcceptChanges()
    End If