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

Discussion in 'ASP .Net' started by keithb, May 3, 2006.

  1. keithb

    keithb Guest

    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


    keithb, May 3, 2006
    1. Advertisements

  2. keithb

    Onwuka Emeka Guest

    To be on the safe side you can change to :
    if(Com != Convert.ToString(rw.ItemArray[0]))
    Onwuka Emeka, May 3, 2006
    1. Advertisements

  3. keithb

    MSDN Guest


    Please explain "on the safe side".

    Thank you,


    MSDN, May 3, 2006
  4. 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.
    =?ISO-8859-1?Q?G=F6ran_Andersson?=, May 7, 2006
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.