Combo Box DisplayMember Value

dukeofawesome

Member
Joined
Mar 22, 2006
Messages
23
Location
Australia
Programming Experience
Beginner
Hi Everyone,

I am trying to get the value from a combo selection, more specifically, the DisplayMember. I have a combo box that is populated using the following code:

VB.NET:
Sub PopComboBox(objCombo As ComboBox, strSQL As String, ValMember As String, DispMember As String)
        dbs.ConnectDB()

        ds = dbs.sqlSelect(strSQL)

        objCombo.DisplayMember = DispMember
        objCombo.ValueMember = ValMember
        objCombo.DataSource = ds.Tables("Results")
        objCombo.Refresh()

        dbs.CloseDB()

End Sub

The combo box gets populated and lists all the relevant data. I can obtain the the selected value like so:

VB.NET:
lblDatabaseID.Text = cmbDataConnection.SelectedValue.ToString

and it returns the correct ID. But when I try and retrieve the Display Member like so:

VB.NET:
lblPath.Text = cmbDataConnection.DisplayMember.ToString

It just returns the field name rather than the data. I've also tried:

VB.NET:
lblPath.Text = cmbDataConnection.SelectedItem.ToString
lblPath.Text = cmbDataConnection.SelectedText.ToString

And it still doesn't work. What am I missing?

Thanks
 
The DisplayMember property is the name of the column or property from which the ComboBox displays data. If you get the DisplayMember then you get that name, NOT the value from the column or property with that name. The SelectedItem is the item itself, not the text displayed for that item and the SelectedText works exactly as it does in a TextBox.

If you want the text displayed for the selected item then you use the Text property. More generally, the GetItemText method will get you the text displayed for any item. If you call GetItemText and specify the SelectedItem as the item then you'll get the same value as Text returns.
 
Back
Top