Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Specified cast is not valid? 1

Status
Not open for further replies.

mtl77

Programmer
May 27, 2003
31
CA

Hello,

I am getting the error "Specified cast is not valid" on the following line of code and i cannot see why:

int _totalRecords = (int) myCommand.Parameters["@TotalRecords"].Value;

@TotalRecords is a an output from a stored procedure from a sql db. It is an int.

Any ideas?

mtl77.
 
Try passing your value to Convert.ToInt32(), a cast may not always work the way you think it should.

"Programming is like sex, one mistake and you have to support it forever."

John

johnmc@mvmills.com
 
Thanks jmcpher, that worked like a charm.

Can you explain why the cast would not work the first way, or is it just one of those things?

Love the quote.

mtl77
 
Should be something like that (missing []):

int _totalRecords = (Int32) myCommand.Parameters["@TotalRecords"].Value;
-obislavu-
 
The Value property returns an object, and that object might not actually be an int. Convert.To*() will take an object, cast it to an IConvertible, and then call its To* function. So basically Convert does the cast by asking the object to please cast itself.

"Programming is like sex, one mistake and you have to support it forever."

John

johnmc@mvmills.com
 
You no need to cast it to IConvertible and then To*:
The followings statements are working very well and is doing that:

int vReturn=0;
vReturn= (Int32)SelectCommand.Parameters["@ReturnValue"].Value;

-obislavu-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top