Help: Unable to cast object of type 'System.Int32' to type 'System.String'.

  • Thread starter Thread starter keithb
  • Start date Start date
K

keithb

What could be causing this?

this code:

String Com = "";
if (Com != (String)rw.ItemArray[0])

fails at runtime with the error message: Unable to cast object of type
'System.Int32' to type 'System.String'.

this code, in a different class runs without error:
String Env = "";
if (Env != (String)rw.ItemArray[0])

Both rw.ItemArray[0] elements are int32 datatypes, both are populated with
the same numerical value

Thanks,

Keith
 
To be on the safe side you can change to :
if(Com != Convert.ToString(rw.ItemArray[0]))
 
Onwuka,

Please explain "on the safe side".

Thank you,

SA

Onwuka Emeka said:
To be on the safe side you can change to :
if(Com != Convert.ToString(rw.ItemArray[0]))

keithb said:
What could be causing this?

this code:

String Com = "";
if (Com != (String)rw.ItemArray[0])

fails at runtime with the error message: Unable to cast object of type
'System.Int32' to type 'System.String'.

this code, in a different class runs without error:
String Env = "";
if (Env != (String)rw.ItemArray[0])

Both rw.ItemArray[0] elements are int32 datatypes, both are populated
with the same numerical value

Thanks,

Keith
 
You can never cast an int to a string. You can only cast an object to
it's actual type or any type that it inherits.

Use the ToString method to convert an int to a string.

Your code doesn't make sense, though. The string representation of an
int could never be equal to an empty string.
 
Back
Top