2013-05-13 174 views
0

對於名爲ALLconn的數組中的每個連接,我想將它與我的sql表進行比較。如果存在,然後添加到我的列表視圖。這裏是我的代碼如下,但它似乎並沒有工作:比較陣列與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 
+1

數組的類型是什麼?表中的列是什麼?什麼構成「匹配」? – 2013-05-13 21:07:43

回答

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 

這是必要的,因爲你原來的代碼中,內部運行直到數據庫加載的數據結束,然後當您嘗試檢查下一個conn時,無法在數據庫加載的數據開始時重新定位閱讀器。

+0

謝謝史蒂夫。您的解決方案奏效 – 2013-05-13 21:19:52

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

其實,你的問題是未完成的,但仍然按我理解你試圖讀取SqlCommand.ExecuteReader()的結果。當你讀到這個結果時,它會從頭到尾閱讀,這是你只能閱讀的一次。如果您嘗試再次閱讀,則會顯示錯誤,因爲沒有更多內容要從對象Loginfilter中讀取。

因此,您可以將該讀數存儲到數組中,並繼續使用您的Foreach,而使用新創建的數組的邏輯或者您可以從LoginFilter讀取數據,並將其與AllConn數組或List中的forech連接進行比較。

如果你需要更多的解釋,請隨時響應我,我會送你在C#版本。