user4945412
user4945412

Reputation: 35

Two values inside a combobox in vb

i want to create a combobox with two fields inside.

so far, this is my code.
it can only display the area number but i want to display also the area name in a single line. can anyone help me with this? any help will be greatly appreciated. thank you so much

  Sub getarea()
    Try
        Call MyConnection()
        Sql = "select AREA_NO as 'Anum', AREA_NAME as 'Aname', AREA_LOCX as 'Alocx' from area"
        Dim cmd As New MySqlCommand(Sql, Con)
        Dim reader As MySqlDataReader
        reader = cmd.ExecuteReader
        Try
            Dim comboarea As New DataTable
            comboarea.Load(reader)
            cboareano2.DataSource = comboarea
            cboareano2.DisplayMember = "Anum"
            cboareano2.ValueMember = "Anum"
            cboareano2.SelectedIndex = -1

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    Catch ex As Exception
        MsgBox(ex.Message)
        Con.Close()
    End Try
End Sub


Private Sub cboAreaNo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboAreaNo.SelectedIndexChanged
    Try
        Call MyConnection()
        Sql = "select AREA_NAME, AREA_LOCX from area where AREA_NO=@Anum"
        Dim cmd As New MySqlCommand
        With cmd
            .CommandText = Sql
            .Connection = Con
            .Parameters.AddWithValue("@Anum", cboAreaNo.SelectedValue)
            .ExecuteNonQuery()
        End With
        Dim reader As MySqlDataReader
        reader = cmd.ExecuteReader
        Try
            If reader.Read Then
                txtlocx.Text = reader.GetString(1)
                reader.Close()
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    Catch ex As Exception
        Con.Close()
    End Try

Upvotes: 1

Views: 135

Answers (1)

user4959983
user4959983

Reputation:

You are makes some mistake in binding the combobox, you are assigning Anum to both DisplayMember field as well as to the ValueMember field. so the SelectedItem and SelectedValue both are the Area_Number`.

So what you have to do is that: Recode the binding snippet as follows

    Dim comboarea As New DataTable
    comboarea.Load(reader)
    cboareano2.DataSource = comboarea
    cboareano2.DisplayMember = "Aname"
    cboareano2.ValueMember = "Anum"
    cboareano2.SelectedIndex = -1
  • Now you can take the Area_Name through cboareano2.Text or cboareano2.SelectedItem.Text
  • You will get the Area_Code through cboareano2.SelectedValue
  • If you want to display both the code and name then make change in the query as follows:

     Sql = "select AREA_NO as 'Anum', CONCAT(AREA_NO,'-',AREA_NAME) as 'Aname', AREA_LOCX as 'Alocx' from area"
    

    and bind the result as i mentioned above.

Upvotes: 1

Related Questions