如何处理无效的强制转换异常错误 [英] how to handle Invalid cast exception error

查看:114
本文介绍了如何处理无效的强制转换异常错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误 [无法将'System.DBNull'类型的对象强制转换为'System.String'。] 此行doc.Dr_Remarks =(string)Reader [ Dr_Remarks] ;.



我的datareader从DB中带来空值。所以请帮我如何在c#中的这一行处理异常。

解决方案

这个也会尝试转换为string 。但是,如果转换不可行, 关键字将返回null而不是抛出异常:

 doctor.Dr_Remarks = Reader [  Dr_Remarks]  as   string ; 

你需要考虑的是:

你真的吗?如果数据库存储了DBNull,想要获取空值吗?

或者你想在这里进行一些错误处理吗?

或者你是否因为null而进行分支在Dr_Remarks中?


您好Murugappan,



包含此代码以处理DataReader中的空值。

  if (!dataReader.IsDBNull(columnIndexNo))
return dataReader.GetString(columnIndexNo);
else
return string .Empty;


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#.

解决方案

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:

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?


Hi Murugappan,

Include this code to handle the null values from the DataReader.

if(!dataReader.IsDBNull(columnIndexNo))
       return dataReader.GetString(columnIndexNo);
   else
       return string.Empty;


这篇关于如何处理无效的强制转换异常错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆