0

When I run this code my listbox is empty. What is the best way to get data from SQL and into a listbox? When the form is submitted I want to use the CustomreID value data to store into another table and thought using the index would be the best solution.

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
3
  • is this webform? or winforms? Commented Jan 24, 2013 at 21:31
  • check stackoverflow.com/a/9116889/1080742 and lsbDestination.DisplayMember = "Company"; lsbDestination.ValueMember = "CustomerID"; Commented Jan 24, 2013 at 21:38
  • thanks displayMember and ValueMember are what I needed! Commented Jan 25, 2013 at 15:26

2 Answers 2

2

You can easily bind data to a ListBox using the DataSource property of the ListBox. Try something like this (untested):

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

Good luck.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to add a items to ListBox using 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

Just let me know if you've encountered some problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.