Reputation: 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
Upvotes: 1
Views: 135
Reputation:
You are makes some mistake in binding the
combobox
, you are assigningAnum
to bothDisplayMember
field as well as to theValueMember
field. so theSelectedItem
andSelectedValue 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
cboareano2.Text
or
cboareano2.SelectedItem.Text
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