Specified cast is not valid


Well-known member
Jun 7, 2004
Wales, UK
Programming Experience
I'm getting data from a database no problem, but when there is a field with no data in it I encounter this problem:-

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Specified cast is not valid.

Source Error:

Line 32: textboxaddress.text = reader.GetString(7)
Line 33: textboxcity.text = reader.GetString(8)
Line 34: textboxregion.text = reader.GetString(9)

Does anyone know how I can avoid this?


Staff member
Jun 3, 2004
Raleigh, NC - USA
Programming Experience
The problem is most likely that the value being returned is a Null value. The GetString method is expecting a string which the constant System.DbNull.Value is not.

There are several possible solutions.

You could alter the dataBase so that it doesn't contain Null values. In an Access dataBase you do that by changing the field's "Allow Zero Length" property to Yes and either change the "Required" property to Yes or set the "Default Value" to an empty string (""). Making these changes does not alter existing data.

(When asking questions regarding dataBases, it's always best to specify the type of dataBase. That way you may receive more specific solutions geared towards that type of dataBase :) )

If you would rather not do that or already have a substantial amount of data, you can use the GetValue method of the DataReader (as opposed to the GetString method) and check if the value is System.DBNull.Value.

Latest posts

Top Bottom