How to fill listbox from SQL query

I'm writing a small VB.NET app.
How would I fill a list box using an SQL query?
I have a listbox that I need to populate with data from SQL.
I have a username/password/SQL address. SQL query would be (select StockNumber from dbo.VehicleMaster)

Would appreciate a code sample :)

Thanks!
LVL 1
Matrix1000Asked:
Who is Participating?
 
Brian CroweConnect With a Mentor Database AdministratorCommented:
dim conn as new sqlconnection("your connection string here")
dim cmd as new sqlcommand
dim dr as sqldatareader

cmd.connection = conn
cmd.commandtype = commandtype.text
cmd.commandtext = "SELECT StockNumber FROM dbo.VehicleMaster ORDER BY StockNumber" 'ORDER BY clause is optional

try
     cmd.connection.open
     dr = cmd.executereader
     while dr.read
          myListBox.items.add(dr.getvalue(dr.getordinal("StockNumber")).tostring)
     end while
catch ex as SQLException
     messagebox.show (ex.message)
finally
     cmd.connection.close
end try
     
0
 
Jeff CertainCommented:
Is your database SQL server or something else?
0
 
Jeff CertainConnect With a Mentor Commented:
Sorry. Dumb question. The "dbo" should have been a giveaway...

Dim conn as New System.Data.SqlClient.SQLConnection("insert your connection string here")
conn.open
Dim strSQL as string = "select StockNumber from dbo.VehicleMaster"
Dim cmd as New System.Data.SQLClient.SQLCommand(strSQL, conn)
Dim adapter As System.Data.SqlClient.SqlDataAdapter = New System.Data.SqlClient.SqlDataAdapter(cmd)
Dim myTable as System.Data.DataTable = New System.Data.DataTable
adapter.Fill(myTable)
cmd.dispose
conn.close

ListBox1.DataSource = myTable
ListBox1.DataTextField =StockNumber
ListBox1.DataValueField =StockNumber
ListBox1.DataBind
0
 
Jeff CertainCommented:
BriCrowe ,

Nice hijack.
0
 
Matrix1000Author Commented:
BriCrowe's example worked perfectly right off the bat.

Chaosian, VB.net had issues with
        lstStocknumberList.DataSource = myTable
        lstStocknumberList.DataTextField = StockNumber
        lstStocknumberList.DataValueField = StockNumber
        lstStocknumberList.DataBind()
 saying that 'DataTextField' etc is not a member of System.Windows.forms.Listbox.
Thanks for trying tho :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.