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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With