Jul 6th, 2008, 07:04 PM
#1
Thread Starter
Hyperactive Member
[RESOLVED] Invalid cast exception
I'm getting an invalid cast exception which makes no sense whatsoever (see attachment).
It occurs no matter what the number in the cell is.
The ids variable is defined as so:
c# Code:
List<int> ids = new List<int>();
Just below the line creating the error is another line...
c# Code:
link_Main_RFITableAdapter.DeleteID((int)row.Cells[0].Value);
... which contains the same cast. This line does not produce the error whien I run the program without the first line.
Can anyone help? This is pretty urgent: I can't do much until I've fixed it.
Thanks in advance,
Qu.
Attached Images
Last edited by Quasar6; Jul 6th, 2008 at 07:08 PM .
"Why do all my attempts at science end with me getting punched by batman?" xkcd.
|
Pong |
|
Sorry for not posting more often.
Jul 6th, 2008, 07:11 PM
#2
Re: Invalid cast exception
According to your screen shot the cell's Value property contains a string, not an int. If it was an int it wouldn't have the double quotes around it, which indicate a string literal.
Jul 6th, 2008, 07:13 PM
#3
Re: Invalid cast exception
Note that you can convert a string to an int, assuming the value is valid, but you cannot cast a string as an int. To cast one of the types must inherit or implement the other, i.e. there must be an IS A relationship between the two types. Neither string nor int inherit the other so there is no such relationship, so there is no valid cast.
Jul 6th, 2008, 07:19 PM
#4
Thread Starter
Hyperactive Member
Re: Invalid cast exception
Thanks jmc! Using an int.Parse and a ToString() method isn't pretty, but it works.
Code:
ids.Add(int.Parse(row.Cells[2].Value.ToString()));
I just noticed that I wasn't using the same cell index in the second line. No wonder it worked when the first didn't.
*headdesk*
"Why do all my attempts at science end with me getting punched by batman?" xkcd.
|
Pong |
|
Sorry for not posting more often.
Jul 7th, 2008, 07:26 AM
#5
Fanatic Member
Re: [RESOLVED] Invalid cast exception
Or I think you could use System.Convert
C#.net, VB, C++, Java, VS 2005/2008
Dont' forget to rate posts that are helpful to you.
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Click Here to Expand Forum to Full Width