Search ComboBox - error

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi, All
I have to search combobox and when search string will match the item in
combobox collection select it (VB.NET Windows CE Device)
Code below return exception: "Cast from 'Location' to type 'String' is not
valid"

Dim sSearch as String
Dim sItm as String
For Each sItm In cbo.Items
If sSearch.CompareTo(sItm) = 0 Then
i = cbo.Items.IndexOf(sItm)
cbo.SelectedIndex = i
End If
Next

Please help
 
What are you adding to the combobox(showing us a complete example would help
us help you)? BTW, make sure you have Option Strict/Explicit On when coding
in VB.

If you are adding strings it should work but it sounds like you are adding
some "Location" class. In that case declare sItm As Location. Of course
you'll have to modify your comparison criteria.

Finally, after setting the cbo.SelectedIndex, stick a Return so you don't
waste time iterating other items.

Cheers
Daniel
 
The exception occures on the very first statement:
For each sItm in cbo.Items - error "Cast from 'Location' to type 'String' is
not valid"

what is the other option for the search combo?
 
It looks like your combobox items are not strings. Hence the exception. You
can do this:
Dim sSearch as String
For Each Item as Object In cbo.Items
If sSearch.CompareTo(sItm.ToString()) = 0 Then
i = cbo.Items.IndexOf(sItm)
cbo.SelectedIndex = i
End If
Next

Better yet (for the sake of efficiency):

Dim sSearch as String
Dim i as Integer
For i = 0 to cbo.Items.Count - 1
If cbo.Items(i).ToString = sSearch Then
cbo.SelectedIndex = i
Exit For
End If
Next
 
Thank you All for help, i populated combobox from ArrayList, that is why i
got the exception, it works this way:

Dim sItm As Location
Dim sLoc as String
For Each sItm In cbo.Items
If sLoc.CompareTo(sItm.ToString()) = 0 Then
i = cbo.Items.IndexOf(sItm)
cbo.SelectedIndex = i
Exit For
End If
Next
 
Back
Top