Specified cast is not valid

  • Thread starter Web Team @ Borough of Poole
  • Start date
W

Web Team @ Borough of Poole

Can anyone help with this error...

"Specified cast is not valid."


Which I am getting with this code...
(Line 223)

Line 221: 'Handles data paging
Line 222: Public Sub PagerButtonClick(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnPager.Click
Line 223: Dim arg As String = CType(sender,
Button).CommandArgument
Line 224: Select Case arg
Line 225: Case "next" 'The next Button was


I casted sender to button in order to fix a 'late binding' error I had
after switching option strict on.
 
P

Patrice

The CommandArgument is an object if I remember. You'll have to cast it to a
string...

You can use DirectCast for the button and CStr for the CommandArgument...
 
W

Web Team @ Borough of Poole

Thanks Patrice

I tried this:
Dim arg As String = DirectCast(sender, Button).CommandArgument

But it still comes back with the same error.
 
P

Patrice

I meant try :
Dim arg As String=CStr(DirectCast(Sender,Button).CommandArgument)

(IMO the problem is that CommandArgument is an object not a string)

Does it work ?

If not try just :
Response.Write(Sender.GetType.ToString)
Response.Write(Sender.CommandArgument.GetType.ToString)
and adds temporarily Option Strict Off at the top of your source file...

This way it writes down the types and you should then know how to cast them
(think to remove Option Strict Off)...

CType works as well but if I remember DirectCast conduct the fact that
sender *is* a button while with CType you could have a button or whatever
inherits from a button (will fails otherwise, perhaps a bit quicker but
unlikely noticeable). I shouldn't have mentionned this, not relevant here...

Hope I'm a bit clearer now...
 
W

Web Team @ Borough of Poole

Thank you Patrice,

Using your tip to response.write the type, I discovered it was actually
a linkbutton, not a button - Hence the invalid cast.

Much appreciated.

Simon.
 
P

Patrice

Ah great !!! I'm really delighted to see that sometimes it's better to
suggest how to diagnose by yourself a problem rather than trying to solve it
at your place ;-)

Patrice
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top