2011-01-25 106 views
0

在我的數據庫中,一個用戶可以有多個訂單。我想獲得用戶的所有訂單並將其保存在列表中。將SQL結果保存到Lst?

這就是我現在做

Public Function GetUserOrders(ByVal userID As Integer) As DataSet 
     Dim sqlDA As New SqlDataAdapter 
     Dim ds As New DataSet 
     Dim myCommand As New Data.SqlClient.SqlCommand("sp_GetUserOrders", myConnection) 
     ' Mark the Command as a SPROC 
     myCommand.CommandType = CommandType.StoredProcedure 
     Dim muserID As New SqlParameter("@userID", SqlDbType.Int) 
     muserID.Value = userID 
     myCommand.Parameters.Add(muserID) 
     Try 
      ' Open the connection and execute the Command 
      myConnection.Open() 
      sqlDA.SelectCommand = myCommand 
      sqlDA.Fill(ds) 

     Catch ex As Exception 

     Finally 
      myConnection.Close() 
     End Try 

     Return ds 
    End Function 

,但我似乎無法弄清楚如何將結果分配給一個列表。

Dim orderList As New ListItemCollection() 
orderlist = GetUserOrders() 

不起作用,請幫忙。

+1

您正試圖將`DataSet`強制轉換爲`ListItemCollection`。這不會工作,因爲沒有演員存在。你需要通過另一種方法將你的`DataSet`變成`ListItemCollection`。 – 2011-01-25 15:25:26

回答

0

我明白了。

我在getuserorders函數中設置了列表。

Dim dr As SqlDataReader 
     Dim orderList As New ListItemCollection() 
     Try 
      ' Execute the command 
      myConnection.Open() 
      dr = myCommand.ExecuteReader() 

      If Not dr.Read() Then 
       Return Nothing 
      Else 
       While dr.Read() 
        orderList .Add(dr("orderCode")) 
       End While 
      End If 
      dr.Close() 
     Finally 
      myConnection.Close() 
     End Try