1 Attachment(s)
[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.
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.
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.
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*
Re: [RESOLVED] Invalid cast exception
Or I think you could use System.Convert