11
Answers

Object cannot be cast from DBNull to other types (Date)

Ask a question
Chriz L

Chriz L

9y
606
1
Hello,
 
I retrieve data from db through dataset as following:
birthdate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["BirthDate"]).ToString("dd/MM/yyyy");
 
My problem is when the BirthDate is null I get the following exception   "Object cannot be cast from DBNull to other types."
 
I tried:
if (String.IsNullOrEmpty(Convert.ToDateTime(ds.Tables[0].Rows[0]["BirthDate"]).ToString("dd/MM/yyyy").Trim()))
birthdate.Text = null;
else
birthdate.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["BirthDate"]).ToString("dd/MM/yyyy");
 
but I'm still getting the exception. 
 
Any suggestions?
 
Thank you in advance. 

Answers (11)