将数据库显示的数据显示到组合框但值成员不同

时间:2014-04-24 13:58:34

标签: sql vb.net

我从数据库中获取数据并显示到组合框,我想看到名称,但原始值是id ..我在这里有一个代码,请查看我在这里做错了什么。 Public Sub nameshow()

    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)

以下是我在研究之后发生的事情:

您收到了错误消息。很可能“连接已经开放”。然后尝试使用catch语句吞下这个错误。因此,永远不会将数据源添加到组合框中。试试这个:

Public Function SelectRows( _
    ByVal dataSet As DataSet, ByVal connectionString As String, _
    ByVal queryString As String) As DataSet

    Using connection As New SqlConnection(connectionString)
        Dim adapter As New SqlDataAdapter()
        adapter.SelectCommand = New SqlCommand( _
            queryString, connection)
        adapter.Fill(dataSet)
        Return dataSet
    End Using 
End Function

用这个称呼:

objDataSet = SelectRows(objDataSet, "ConnectionString","select * from tblBrand")
With (cboxBrandName)
    .DataSource = objDataSet
    .ValueMember = "tblBrand.BandID"
    .DisplayMember = "tblBrand.BrandName"
End With

我相信这会奏效。