Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB | Loading SQL Query into Combobox

I am trying to fill a combobox with a SQL Result I think my problem is handling the data in the datatable 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 stare at a sad empty combobox.

like image 201
UPGRAYEDD Avatar asked Mar 23 '23 16:03

UPGRAYEDD


2 Answers

Almost right, but you need to Load the datatable using the DataReader.
Then assing the DataTable to the DataSource of the 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

Also you could set the combobox ValueMember property to the name of the column that you will use as key for future processing and the DisplayMember property to the column name that you want to display as text to choose from for your user

like image 158
Steve Avatar answered Apr 02 '23 03:04

Steve


you can also do it as

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 it works for you.

like image 21
SMHasnain Avatar answered Apr 02 '23 05:04

SMHasnain