Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am getting the following error [Unable to cast object of type 'System.DBNull' to type 'System.String'.] at this line doctor.Dr_Remarks = (string)Reader["Dr_Remarks"];.

My datareader is bringing null value from DB . so pls help me how to handle exception at this line in c#.
Posted
Comments
[no name] 30-Aug-13 5:24am    
Okay so why are you unable to check to see that it is not null?

This one will also try to cast to string. But the as keyword returns null instead of throwing an exception if the conversion is not feasible:
C#
doctor.Dr_Remarks = Reader["Dr_Remarks"] as string;
What you have to consider is:
Do you really want to get a null value back if the databas stored DBNull?
Or do you wish to branch into some error handling here?
Or do you branch anyway because of a null in Dr_Remarks?
 
Share this answer
 
Comments
MurugappanCTS 30-Aug-13 7:37am    
I just wanted to get out of error . may be i can show in the grid column the "null" value from database
Hi Murugappan,

Include this code to handle the null values from the DataReader.
C#
if(!dataReader.IsDBNull(columnIndexNo))
       return dataReader.GetString(columnIndexNo);
   else
       return string.Empty;
 
Share this answer
 
Comments
MurugappanCTS 31-Aug-13 0:59am    
Thanks thomas

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900