Search code examples
sqlvb.netvisual-studio-2010combobox

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.


Solution

  • Almost right, but you need to Load the datatable using the DataReader.
    Then assign 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