VB | Loading SQL query into Combobox

I am trying to populate a combobox with SQL result. I think my problem is processing data in data form.

Dim sql As String Dim sqlquery As String Dim ConnectionString As String ConnectionString = "Data Source=(local);Initial Catalog=Control;Persist Security Info=True;User ID=user;Password=pass" sqlquery = "Select dbName from Databases" Using connection As SqlConnection = New SqlConnection(ConnectionString) connection.Open() Using conn As SqlCommand = New SqlCommand(sqlquery, conn) Dim rs As SqlDataReader = comm.ExecuteReader Dim dt As DataTable = New DataTable dt.Load(cmboxDatabaseName) End Using 'comm End Using 'conn 

When I run the program, I just look at the sad empty combo box.

+4
source share
2 answers

Almost correct, but you need to load data using DataReader.
Then, casting the DataTable to a DataSource Combo

 Using connection As SqlConnection = New SqlConnection(ConnectionString) connection.Open() Using comm As SqlCommand = New SqlCommand(sqlquery, connection) Dim rs As SqlDataReader = comm.ExecuteReader Dim dt As DataTable = New DataTable dt.Load(rs) ' as an example set the ValueMember and DisplayMember' ' to two columns of the returned table' cmboxDatabaseName.ValueMember = "IDCustomer" cmboxDatabaseName.DisplayMember = "Name" cmboxDatabaseName.DataSource = dt End Using 'comm End Using 'conn 

You can also set the combobox ValueMember property to the column name that you will use as a key for future processing, and the DisplayMember property to the column name that you want to display as text of your choice

+5
source

you can also do it like

 Dim Con = New SqlConnection(_ConnectionString) Dim cmdAs New SqlCommand Dim dr As New SqlDataReader Try If Con.State = ConnectionState.Closed Then Con.Open() cmd.Connection = Con cmd.CommandText = "Select field1, field2 from table" dr = cmd.ExecuteReader() ' Fill a combo box with the datareader Do While dr.Read = True ComboBoxName.Items.Add(dr.GetString(0)) ComboBoxName.Items.Add(dr.GetString(1)) Loop Con.Close() End If Catch ex As Exception MsgBox(ex.Message) End Try 

Hope this works for you.

+1
source

Source: https://habr.com/ru/post/1484911/


All Articles