weird InvalidCastException

  • Thread starter Thread starter LarryMac
  • Start date Start date
L

LarryMac

Here's my dilemma. I have a listbox that the user can select an item
("OrderItem" class) from, provided it hasn't already been selected (in
which case it will appear on a second list box). The following
procedure checks list2 (passed as lstSearch). It works fine the first
time through, but if the user attempts to add a second item, the
function crashes - throwing an Invalid castException on the indicated
line, saying that "Cast from type 'OrderItem' to type 'String' is not
valid."...despite the fact that it will work fine the first time
through!

Private Function OnList(ByVal strSearch As String, ByVal lstSearch As
ListBox) As Boolean

'Declare variables
Dim blnFound As Boolean
Dim intListIndex As Integer = 0

Do Until blnFound Or intListIndex = lstSearch.Items.Count
*If strSearch = CStr(lstSearch.Items(intListIndex)) Then*
blnFound = True
End If
intListIndex += 1
Loop
Return blnFound
End Function

Any thoughts?
 
While I can't swear that I tried the findstring, I know I was having
problems originally because the list items are objects (passed using
the ToString function)and not straight text (or strings, for that
matter).

The thing that's bothering me is that if the user removes the item
from list2 (doubleclicking list2 items removes them), the boolean
serach will work again. So I can use it as often as I want, as long
as there's nothing currently in list2.

BTW, I tried changing the code to display the "Already selected"
message box on True instead of False and it gave me the message box,
so I know that the search is working and returning the false. Plus,
it's code I copied over from another working program in which list2 is
compared against a text entry. If any of that helps and.or makes
sense.
 
Hi Larry,

I think I get it, can you try this

*If strSearch =
Directcast(lstSearch.Items(intListIndex),OrderItem).toString Then*

I hope this helps?

Cor
 
Back
Top