0

当我运行此代码时,我listbox是空的。从 SQL 中获取数据并进入listbox. 提交表单时,我想使用CustomreID值数据存储到另一个表中,并认为使用索引是最好的解决方案。

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
4

2 回答 2

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()

祝你好运。

于 2013-01-24T21:24:43.180 回答
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

如果您遇到问题,请告诉我。

于 2013-01-24T22:15:15.863 回答