Reading Empty Cells

haroldjclements

Freshman
Joined
Jun 13, 2004
I have a problem with reading null value from my database. The connection works and does retrieve the data. However if there is an empty cell in the database it creates an exception “java.lang.classCastException: Specified cast is not valid”

Code:
while (myDataReader.Read())
{
	description = myDataReader.GetString(0);
	//The error is here!
	custPN = System.Convert.ToString(myDataReader.GetString(2));
	//custPN = myDataReader.GetString(2);
	sql = "SELECT Name FROM tblSupplier WHERE SupplierID = " + myDataReader.GetInt16(1);
}

I have tried to convert the output to a string, but that did not work. I think that the problem is with the .GetString() line as a blank cell is not a string. This cell is not always empty so .GetString() works fine when it's not.

If anyone could help me I will be eternally grateful
 

samsmithnz

Senior Contributor
Joined
Jul 22, 2003
Location
Boston
Try checking to see if the value is null before assigning it to the string. You'll find this alot quicker than catching an exception.
 

haroldjclements

Freshman
Joined
Jun 13, 2004
Hello, I know it’s been a long time since your post but I have come across the same problem again.

How would you check to see if the item being dragged from the database is null?

If I use the ‘myDataReader.GetString(x)’ within an ‘if’ statement then I still get the error, so presumably I need to test the object before the conversion.

My question is how?

Thanks in advance,
Harold Clements
 

haroldjclements

Freshman
Joined
Jun 13, 2004
Ok found it:

Code:
if (myDataReader.IsDBNull(5)){textBox3.set_Text("");}
else {textBox3.set_Text(myDataReader.GetString(5));}

Cheers,
Harold Clements
 
Top Bottom