4

我正在尝试用 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

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

4

2 回答 2

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

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

于 2013-06-06T20:26:54.810 回答
1

你也可以这样做

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

希望对你有效。

于 2013-06-07T08:12:53.573 回答