none
How to Display Two Tables' Fields to a Combobox DisplayMember in VB.Net

    Question

  • I have two tables; 'kelas' and 'subkelas'. 'kelas' table contains 'kelas_id' and 'name' field while 'subkelas' table contains 'subkelas_id', 'kelas_id' and 'name'.

    Here my code to display the tables in combobox

     

        Sub myCombo()
            Dim myCommand As New MySqlCommand
            Dim myAdapter As New MySqlDataAdapter
            Dim myData As New DataTable
            Dim SQL As String
            Dim th_akad As String
            th_akad = "22"
            SQL = "SELECT skls.name, skls.subkelas_id, kls.name " _
             & "FROM tbl_subkelas skls INNER JOIN tbl_kelas kls ON skls.kelas_id = kls.kelas_id WHERE skls.th_akad_id = '" & th_akad & "'"
    
    
    
            Try
                myCommand.Connection = conn
                myCommand.CommandText = SQL
                myAdapter.SelectCommand = myCommand
    
                myAdapter.Fill(myData)
    
                cmbKelas.DataSource = myData
                cmbKelas.DisplayMember = "subkelas"
                cmbKelas.ValueMember = "subkelas_id"
            Catch myerror As MySqlException
                MsgBox("There was an error reading from the database: " & myerror.Message)
            End Try
    
        End Sub
    

     


    This code only displays field 'name' of 'subkelas' table.

    My question: is it possible to display the 'name ' fields from both tables in DisplayMember? (eg. "XII Extension A"). 'XII' retrieve from 'name' of 'kelas' table and 'Extension A' from 'name' of 'subkelas' table.

    Thanks ......


    • Edited by Manshub Sunday, November 20, 2011 5:44 PM
    Sunday, November 20, 2011 5:28 PM

Answers

  • > My question: is it possible to display the 'name ' fields from both tables in DisplayMember?


    yes, you can with a DataColumn.Expression define 'virtual' column and bind to the combobox.
    something linke this: myData.Tables[0].Columns.Add("vc", typeof(string), "col1+' '+col2");
    -- col1 and col2 is a columns in the table.

    Monday, November 21, 2011 3:53 AM

All replies

  • > My question: is it possible to display the 'name ' fields from both tables in DisplayMember?


    yes, you can with a DataColumn.Expression define 'virtual' column and bind to the combobox.
    something linke this: myData.Tables[0].Columns.Add("vc", typeof(string), "col1+' '+col2");
    -- col1 and col2 is a columns in the table.

    Monday, November 21, 2011 3:53 AM
  • something linke this: myData.Tables[0].Columns.Add("vc", typeof(string), "col1+' '+col2");
    -- col1 and col2 is a columns in the table.


    Hi guys,

    Malobukv's solution is great expect myData is a DataTable and I think the sample should be myData.Columns.Add("vc", typeof(string), "col1+' '+col2");.

    Anyway, this is really a good solution.

    Have a nice day.


    Bob Wu [MSFT]
    MSDN Community Support | Feedback to us
    Tuesday, November 22, 2011 6:37 AM