• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 389
  • Last Modified:

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!
0
Matrix1000
Asked:
Matrix1000
  • 3
2 Solutions
 
Jeff CertainCommented:
Is your database SQL server or something else?
0
 
Brian CroweCommented:
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:
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now