So, you have code and you have an error message that tells you what is wrong, but you made no effort to find out what that error message means? I don't want to discourage you from using this forum but it should not be your first option. Your first option should always be to read the relevant documentation if there is some, then to search the web for relevant information. If you haven't searched the web for keywords like "c# what is a cast" then you haven't really tried to solve your problem. Forums like this one should be a place to get help with problems that you are not able to solve on your own, not problems that you haven't bothered to try to solve on your own. If you want to improve as a developer then you need to learn how to find information for yourself rather than wait for someone else to hand it to you, because it's something that we all have to do most days.
That said, I'll give you this one for free, but you really ought to be able to show what you've already tried in future. In this case, the cast is the (int)
part. The Value
of a DataGridViewCell
is type Object
, because it can store any type of object, so if you want to use the actual value as an int
then you must cast it as type int
. The error message is telling you that that cast is invalid, which means that the cell does not contain an int
value. You can only use a cast where the object being cast actually is the type it is being cast as. If your cell might not then it's up to you to perform the appropriate validation and/or conversion and only cast if you know you have a value of the desired type.