当前位置 : 主页 > 编程语言 > c语言 >

VB |将SQL查询加载到Combobox中

来源:互联网 收集:自由互联 发布时间:2021-06-24
我试图用SQL结果填充组合框 我认为我的问题是以数据表格形式处理数据. Dim sql As String Dim sqlquery As String Dim ConnectionString As String ConnectionString = "Data Source=(local);Initial Catalog=Control;Persist
我试图用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

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

几乎是正确的,但您需要使用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

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

网友评论