Task return field in ms sql 2005 - System.InvalidCastException:

Using the code below I am returning an nvarchar field from MS SQL 2005 and keep getting System.InvalidCastException.

vo.PlacementID = dr.IsDBNull(0) ? null : dr.GetString(0);

      

The variable vo.PlacementID is of type String, so there should be no problem. The values โ€‹โ€‹I'm trying to return look like this (number, number, letter): 00F, 02A, 01F, etc.

System.InvalidCastException: Unable to cast object of type 'System.Int32' to 
type 'System.String'.
    at System.Data.SqlClient.SqlBuffer.get_String()
    at System.Data.SqlClient.SqlDataReader.GetString(Int32 i)

      

Any help is greatly appreciated.

+1


source to share


3 answers


If you read the exception again, this will give you a clue to the problem:

System InvalidCastException : Unable to overlay object of type 'System.Int32' on type 'System.String' . at System.Data.SqlClient.SqlBuffer.get_String () at System.Data.SqlClient.SqlDataReader.GetString (Int32 i)

Basically the underlying datatype returned in column 0 of your SqlDataReader is not string compatible, so the cast exception.



I suggest setting a breakpoint on the offending line and then executing the following line in the nearest window:

? dr.GetValue(0).GetType()

      

This will tell you what type will be returned.

+1


source


the cast exception does not occur in the assignment, but in the datareader GetString ().



try dr.GetValue (0) .ToString ()

+1


source


InvalidCastException

does not arise from a type incompatibility between property PlacementID

and string

. If so, you will get a compile-time error. The problem is that the first field in the result set is not string

, it is something else.

0


source







All Articles