Specified cast is not valid

levyuk

Well-known member
Joined
Jun 7, 2004
Messages
313
Location
Wales, UK
Programming Experience
3-5
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?
 
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.
 
Back
Top