VB |将SQL查询加载到组合框 [英] VB | Loading SQL Query into Combobox

查看:121
本文介绍了VB |将SQL查询加载到组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用SQL结果
填充组合框,我认为我的问题是在处理数据表表单中的数据。

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

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

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

这篇关于VB |将SQL查询加载到组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆