ComboBox select Values How?

  • Thread starter Thread starter Eric
  • Start date Start date
E

Eric

Im populating a combobox from query results like that
below. This works great for populating the box, but I dont
want the selected text, but the ID info associated with
the selection. The query returns Name,ID. I only want to
display the Name in the box, but pull the ID value as the
selected value. I could do this with web forms in .net,
but not with Windows forms controls. Any help would be
great.
EXAMPLE:
Dim dreader As SqlClient.SqlDataReader
DTE.Open()
dreader = SelectExpense.ExecuteReader()
While dreader.Read()
CBO_EType.Items.Add(dreader(0).ToString())
End While
..
 
Eric,

Use the DisplayMember and ValueMember properties of the ComboBox. Code
example follows:


Private loading As Boolean

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim cn As New SqlConnection("Server=(local);Database=Pubs;Integrated
Security=SSPI")
Dim da As New SqlDataAdapter("SELECT au_lname, au_id FROM Authors",
cn)
Dim dt As New DataTable

loading = True
da.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "au_lname"
ComboBox1.ValueMember = "au_id"
loading = False
End Sub

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ComboBox1.SelectedIndexChanged
If Not loading Then
MsgBox(ComboBox1.SelectedValue.ToString)
End If
End Sub
 
Eric,

Use the DisplayMember and ValueMember properties of the ComboBox. Code
example follows:

--
Rob Windsor
G6 Consulting
Toronto, Canada



Private loading As Boolean

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim cn As New SqlConnection("Server=(local);Database=Pubs;Integrated
Security=SSPI")
Dim da As New SqlDataAdapter("SELECT au_lname, au_id FROM Authors",
cn)
Dim dt As New DataTable

loading = True
da.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "au_lname"
ComboBox1.ValueMember = "au_id"
loading = False
End Sub

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ComboBox1.SelectedIndexChanged
If Not loading Then
MsgBox(ComboBox1.SelectedValue.ToString)
End If
End Sub
 
Thanks Rob, It seems like a ton of overhead; populating a
dataset then binding to it, but whatever works.
much thanks, Eric
 
Back
Top