2013-01-24 79 views
0

當我運行此代碼時,我的listbox爲空。從SQL獲取數據並進入listbox的最佳方式是什麼?提交表單時,我想使用CustomreID值數據存儲到另一個表中,並認爲使用索引將是最佳解決方案。將sql數據插入到列表框中

sSQL = "SELECT CustomerID, Company from Customers Order by Company ASC" 

cmd = New SqlCommand(sSQL, moConn) 
rs = cmd.ExecuteReader() 

While rs.Read 
    lsbDestination.Items.Insert(CInt(rs("CustomerID")), rs("Company")) 
End While 
+0

is this webform?或winforms? – spajce

+0

它是一個winforms – user1791536

+0

檢查http://stackoverflow.com/a/9116889/1080742和 'lsbDestination.DisplayMember =「Company」; lsbDestination.ValueMember =「CustomerID」;' – spajce

回答

2

您可以使用ListBox的DataSource屬性輕鬆地將數據綁定到ListBox。嘗試類似的東西(未經測試):

Dim adapter As New SqlDataAdapter(cmd) 
Dim ds As New DataSet 
adapter.Fill(ds) 

lsbDestination.DataTextField = "Company" 
lsbDestination.DataValueField = "CustomerId" 
lsbDestination.DataSource = ds.Tables(0) 
lsbDestination.DataBind() 

祝你好運。

0

如果你想添加一個項目到ListBox使用While rs.Read

Using rsAs SqlDataReader = cmd.ExecuteReader() 
    While rs.Read() 
     Dim items As Object() = {r("CustomerID"), r("Company").ToString()} 
     listBox1.Items.Add(items) 
    End While 
    listBox1.DisplayMember = "Company" 
    listBox1.ValueMember = "CustomerID" 
End Using 

只要讓我知道你是否遇到過一些問題。

相關問題