如何将数据从数据库拉到组合框

时间:2014-04-24 18:44:20

标签: sql vb.net

我正在尝试将数据从数据库拉到组合框,我有2个组合框,我想显示来自不同表的数据。 这是我正在尝试的代码。

Try
        'declare variables

        Dim objDataAdapter As New SqlDataAdapter
        Dim objDataAdapter1 As New SqlDataAdapter
        Dim objDataSet As New DataSet()
        Dim objDataSet1 As New DataSet()

        '//state dataset of combo box
        ' Set the SelectCommand properties...
        objDataAdapter.SelectCommand = New SqlCommand()
        objDataAdapter.SelectCommand.Connection = sql.SqlConn
        objDataAdapter.SelectCommand.CommandText = "select * from tblBrand"
        objDataAdapter.SelectCommand.CommandType = CommandType.Text
        '//mention the second data 
        objdataadapter1.SelectCommand = New SqlCommand()
        objDataAdapter1.SelectCommand.Connection = sql.SqlConn
        objDataAdapter1.SelectCommand.CommandText = "select * from tblModel"
        objDataAdapter1.SelectCommand.CommandType = CommandType.Text

        ' Open the database connection...
        sql.SqlConn.Open()
        ' Fill the DataSet object with data...
        objDataAdapter.Fill(objDataSet, "tblBrand")
        objDataAdapter1.Fill(objDataSet1, "tblModel")
        ' Close the database connection...
        sql.SqlConn.Close()

        With (cboxBrandName)
            .DataSource = objDataSet
            .ValueMember = "tblBrand.BandID"
            .DisplayMember = "tblBrand.BrandName"
        End With
        With (cboxModel)
            .DataSource = objDataSet1
            .ValueMember = "tblModel.ModelID"
            .DisplayMember = "tblModel.ModelName"
        End With

    Catch ex As Exception
    End Try
End Sub

在这一行没有显示任何错误但我在组合框中找不到任何结果。

1 个答案:

答案 0 :(得分:0)

我是这样做的 -

    Dim ds As New DataSet()
    Dim conn As New SqlConnection(yourconnectionString)

    Const qry As String = "SELECT * FROM tblModel"

    conn.Open()
    Using da As New SqlDataAdapter(qry, conn)
        da.Fill(ds)
    End Using
    ' For Combobox

    With YourComboBoxName
        .DisplayMember = "what you want to display to the user in combobox"
        .ValueMember = "ID associated with each record"
        .DataSource = ds.Tables(0)
        .SelectedIndex = 0
    End With

    conn.Close()

希望这有帮助。