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?
 

Paszt

Staff member
Joined
Jun 3, 2004
Messages
1,500
Location
Raleigh, NC - USA
Programming Experience
Beginner
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.
 

cpopham

Member
Joined
Jun 3, 2004
Messages
20
Programming Experience
1-3
Are you using a datareader or a dataadpter?


Chester
 

suddenelfilio

Well-known member
Joined
Jun 3, 2004
Messages
144
Location
Belgium
Programming Experience
5-10
If i'm not mistaken if you use convert.tostring( reader.GetString(9)) will return an empty string when there is a DBNULL value and not throw an exception.
 

Paszt

Staff member
Joined
Jun 3, 2004
Messages
1,500
Location
Raleigh, NC - USA
Programming Experience
Beginner
If the GetString method is used and a value other than a string is returned I believe an exception will be thrown.
 
Top Bottom