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.
source to share
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.
source to share