Link to home
Start Free TrialLog in
Avatar of Buck Beasom
Buck BeasomFlag for United States of America

asked on

Combo Box ValueMember/Selected Value

With EE help I have managed to get a working Combo Box that loads sales reps using the code attached.

I want to capture the UserID (which is the ValueMember) in the combo box as a long integer so I can use it for filter a list view. But with what I have so far, my cboSalesRep.ValueMember is null. So I am missing something.

THANKS FOR ANY HELP.
Private Sub cboSalesRep_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboSalesRep.SelectedIndexChanged
        'Set the Public variable to the Combo Box Value
        lngSelectedSalesRepID = CLng(Me.cboSalesRep.SelectedValue)
    End Sub

Open in new window

Avatar of TheMozz
TheMozz
Flag of United States of America image

Try using the Items property along with the selected index property:

lngSelectedSalesRepID = CLng(Me.cboSalesRep.Items[Me.cboSalesRep.SelectedIndex].Value)
Avatar of Carl Tawn
SelectedValue will only work with DataBinding. You need to cast the SelectedItem to your custom type and retrieve the ID from it.
Avatar of Buck Beasom

ASKER

The Mozz plan throws an error. VB doesn't seem to like that syntax.

Carl, you've gotten me this far (and I thought I'd give you a break!) I don't know how to code "cast the SelectedItem to your custom type". I'm WAY new at this.

Thanks.
Something like:

      Dim item As ListItem = CType(cboSalesRep.SelectedItem, ListItem)
      Dim id As Integer = item.ID
Does it help to add a call to ToString() at the end of your code:

lngSelectedSalesRepID = CLng(Me.cboSalesRep.SelectedValue.ToString)

Ref: https://www.experts-exchange.com/questions/23230044/Get-a-Value-from-Combo-Box-in-VB-NET-Winforms.html
Carl:

I put the code in the cboSalesRep_SelectedIndexChanged event.

The comma after SelectedItem throws an error.
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Saying "YOU DA MAN."

I tried to combine two steps into 1, so instead of using CType the way you had it, and then setting the lngSelectedRepID variable to the resulting id value, I tried using Clng.

When I did it this way:
Private Sub cboSalesRep_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboSalesRep.SelectedIndexChanged
        'Set the Public variable to the Combo Box Value
        Dim item As ListItem = CType(cboSalesRep.SelectedItem, ListItem)
        Dim lngItemID As Long = item.ID

        lngSelectedSalesRepID = lngItemID
    End Sub

It worked like a charm!

Thanks again!!!!