VB | 将SQL查询加载到Combobox中

UPG*_*EDD 4 sql vb.net combobox visual-studio-2010

我试图用SQL结果填充组合框我想我的问题是处理数据表格式的数据.

    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
Run Code Online (Sandbox Code Playgroud)

当我运行程序时,我只是盯着一个悲伤的空组合框.

Ste*_*eve 6

几乎是正确的,但您需要使用DataReader加载数据表.
然后将DataTable分配给Combo的DataSource

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
Run Code Online (Sandbox Code Playgroud)

您还可以将组合框ValueMember属性设置为将用作将来处理的键DisplayMember的列的名称,将属性设置为要显示为用户可供选择的文本的列名称