Two values inside a combobox in vb

帅比萌擦擦* 提交于 2020-01-05 08:52:35

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/31601711/two-values-inside-a-combobox-in-vb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!