Vb.net 如何将sql查询值存储到数组中

Vb.net 如何将sql查询值存储到数组中,vb.net,Vb.net,如何将检索到的所有productid存储到数组中 Dim sql As String = "Select ProductID From OrderDetail Order By ProductID Desc" Dim command As New SqlCommand(sql, connection) Dim reader1 As SqlDataReader = command.ExecuteReader() EDIT:但是,我不会返回数组,而是返回一个整数的通用列表(如果您只

如何将检索到的所有productid存储到数组中

Dim sql As String = "Select ProductID From OrderDetail Order By ProductID Desc"
    Dim command As New SqlCommand(sql, connection)
    Dim reader1 As SqlDataReader = command.ExecuteReader()
EDIT:但是,我不会返回数组,而是返回一个整数的通用列表(如果您只想返回ProductId)或一个
ProductClass
对象的列表

Dim list As New List(Of Integer)

Using reader As SqlDataReader = command .ExecuteReader()
    While reader.Read()
        list.Add(reader.GetInt32(reader.GetOrdinal("ProductID")))
    End While
End Using
'check  list.ToArray() now
编辑2:根据评论, 要检索标签文本中的put,可以执行以下操作

Private Function GetProductIDs() As IList(Of Integer)

    Dim list As New List(Of Integer)
    Dim conStr = "write your connection string here"

    Using connection As New SqlConnection(conStr )
        Dim sql As String = "Select ProductID From OrderDetail Order By ProductID Desc"
        Dim command As New SqlCommand(sql, connection)
        Using reader As SqlDataReader = command.ExecuteReader()
            While reader.Read()
                list.Add(reader.GetInt32(reader.GetOrdinal("ProductID")))
            End While
        End Using
    End Using

    Return list

End Function
假设
Label1
是标签控件的ID。
String.Join
方法将返回一个ProductId字符串,用逗号分隔,如
“1,2,6,7”


如何将列表中的所有值检索到label.text?”While reader.Read()Sum.text=(reader(“ProductID”))End While Loop While reader.NextResult()'嘿,如何从列表中获取前3项?@Fredhome:您可以更新查询以返回
前3项
,或者在我们的列表上应用
TAKE
功能
Dim str As String
str = String.Join(",", GetProductIDs())
Label1.Text=str;
SQLdr = SQLCmd.ExecuteReader 'Gets Data

While dr.Read() 'While Data is Present        
      MsgBox(dr("Column Name")) 'Show data in a Message Box
End While

Loop While SQLdr.NextResult() 'Move to the Next Record