Using the code below, I am returning an nvarchar field from MS SQL 2005 and keep getting a System.InvalidCastException.
vo.PlacementID = dr.IsDBNull(0) ? null : dr.GetString(0);
The vo.PlacementID variable is of type String so there shouldn’t be a problem. The values I am trying to return are 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 much appreciated.
If you read the exception again it gives you a clue as to the problem:
Basically the underlying data type being returned in column 0 of your SqlDataReader isn’t a string compatible type, hence the cast exception.
I’d suggest setting a breakpoint on the offending line and then execute the following line in the immediate window:
This will tell what type being returned.