tags:

views:

227

answers:

3

Hi, Using the code below, I am returning an nvarchar field from ms sql 05 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.

A: 

The InvalidCastException isn't raised because of the type incompatibility between the PlacementID property and string. If that was the case, you'd get a compile-time error. The problem is the first field in the result set is not a string, it's something else.

Mehrdad Afshari
A: 

If you read the exception again it gives you a clue as to the problem:

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)

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:

? dr.GetValue(0).GetType()

This will tell what type being returned.

HTH
Kev

Kev
+1  A: 

the cast exception is not raised in the assignment, but in the datareader's GetString().

try dr.GetValue(0).ToString()

devio