System.InvalidCastException: Specified cast is not valid.

C

chrisshearier

The below statement is causing System.InvalidCastException: Specified
cast is not valid. Can anyone see what is going wrong with this and
help me out.

string statement =
Convert.ToString("Select ConfNum from Call" +
" where AcctNo = '" + r["AcctNo"] + "'" +
" AND BegDate = '" + DateOfCall + "'" +
" AND (BegTime between '" + ((DateTime)r["BegDate"]).TimeOfDay + "'"
+
" AND '" + ((DateTime)r["BegDate"]).AddMinutes(30).TimeOfDay +
"')" +
" OR (BegTime between '" + ((DateTime)r["BegTime"]) + "'" +
" AND '" + ((DateTime)r["BegTime"]).AddMinutes(30) + "'");

Thanks,
IndyChris
 
M

Michael C

The below statement is causing System.InvalidCastException: Specified
cast is not valid. Can anyone see what is going wrong with this and
help me out.

string statement =
Convert.ToString("Select ConfNum from Call" +
" where AcctNo = '" + r["AcctNo"] + "'" +
" AND BegDate = '" + DateOfCall + "'" +
" AND (BegTime between '" + ((DateTime)r["BegDate"]).TimeOfDay + "'"
+
" AND '" + ((DateTime)r["BegDate"]).AddMinutes(30).TimeOfDay +
"')" +
" OR (BegTime between '" + ((DateTime)r["BegTime"]) + "'" +
" AND '" + ((DateTime)r["BegTime"]).AddMinutes(30) + "'");

Thanks,
IndyChris

Something returned from the datareader (presumably r is a datareader) cannot
be converted to DateTime, possibly a value that is DBNull.Value. You should
definately break this up into more lines and remove the Convert.ToString.

Michael
 
B

Bjorn Abelli

The below statement is causing System.InvalidCastException:
Specified cast is not valid. Can anyone see what is going
wrong with this and help me out.

There is one superfluous "conversion", and two possible sources to the
error.

As you concatenate everything into a string anyway, there's no need to
convert that string into a string... (unnecessary Convert.ToString).

The two possible sources for the error you're getting:

r["AcctNo"]
DateOfCall

What are the types of those?

Do they have an implicit conversion to string, e.g. by a ToString()-method?

I would guess that the first one doesn't...

I would suggest you instead have this format of the statement:

string statement =
"Select ConfNum from Call " +
" where AcctNo = ? " +
" AND BegDate = ? " +
" AND (BegTime between ? AND ? )" +
" OR (BegTime between ? AND ? )";

....and use Parameters to insert the values instead of concatenation.

// Bjorn A
 

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

Top