0

对于名为 ALLconn 的数组中的每个连接,我想将其与我的 sql 表进行比较。如果存在,则添加到我的列表视图。下面是我的代码,但它似乎不起作用:

Dim LoginFilter As Object
    Dim SelCurrAllSessions As SqlClient.SqlCommand = New SqlClient.SqlCommand("Select * from CurrAllSessions", LFcnn)
    SelCurrAllSessions.CommandType = CommandType.Text
    LoginFilter = SelCurrAllSessions.ExecuteReader

    For Each conn In AllConn
        While LoginFilter.Read()

            If conn.UserName.ToString() = LoginFilter.Item(0) Then
                ListBox1.Items.Add(LoginFilter.Item(0))

            End If
        End While
    Next
4

3 回答 3

1

那么你需要改变循环的顺序

While LoginFilter.Read()
    For Each conn In AllConn
        If conn.UserName.ToString() = LoginFilter.Item(0).ToString Then
            ListBox1.Items.Add(LoginFilter.Item(0).ToString)
            Exit For
        End If
    Next
End While

这是必要的,因为在您的原始代码中,内部运行直到从数据库加载的数据结束,然后当您尝试检查下一个连接时,您无法将阅读器重新定位在数据库加载的数据的开头。

于 2013-05-13T21:10:47.250 回答
0

反过来,用于Contains检查字符串是否包含在集合中,然后您可以将其添加到ListBox

Using LoginFilter = SelCurrAllSessions.ExecuteReader()
    While LoginFilter.Read()
        Dim connection = LoginFilter.GetString(0)
        If AllConn.Contains(connection) Then
            ListBox1.Items.Add(connection)
        End If
    End While
End Using
于 2013-05-13T21:16:19.827 回答
-1

实际上,您的问题尚未完成,但根据我的理解,您尝试读取 SqlCommand.ExecuteReader() 的结果。当您阅读该结果时,它将从头到尾阅读,并且您只能阅读一次。如果您尝试再次阅读,它将显示错误,因为没有更多内容可以从对象 Loginfilter 中读取。

因此,您可以将该读数存储到一个数组中并继续使用新创建的数组的 Foreach 和 while 逻辑,或者您可以从 LoginFilter 读取并比较 AllConn 数组或 List 中的 forech 连接。

如果您需要更多解释,请随时回复我,我将以 C# 版本发送给您。

于 2013-05-13T22:10:37.993 回答