如果单元格可能为空,从数据行读取的正确方法是什么
我有以下代码,如果数据行(dr)中的列为空,它似乎会崩溃。从数据行中解析出值并处理空检查的正确方法是什么?
Person person = new Person()
{
FirstName = dr["FirstName"].ToString(),
LastName = dr["LastName"].ToString(),
BusinessPhoneNumber = dr["BusinessPhone"].ToString(),
I have the following code which seems to blow up if the column in the datarow (dr) is null. what is the correct way to parse out the value from the data row and handle null checks?
Person person = new Person()
{
FirstName = dr["FirstName"].ToString(),
LastName = dr["LastName"].ToString(),
BusinessPhoneNumber = dr["BusinessPhone"].ToString(),
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果该列的类型为字符串,但可以为空,那么尝试:
或
If the column is of type string, but is nullable, what about trying:
or
我相信,数据单元格为空不能成为您问题的原因。也许该列不存在,或者发生了任何其他错误,或者 DataRow 本身为空,您应该处理该问题。查看异常 - “似乎爆炸”并不是对您的问题的有效描述。
下面解释一下,同时也为大家解答一下标题中的问题。
如果列值为 null,则返回对象
System.DBNull
,.ToString()
返回空字符串,而(string)
或作为字符串
返回null
。因此,检查返回的项目是否为
==null
是没有意义的,因为它永远不会计算为true
。DBNull
情况。null
,请将.ToString()
更改为as string
。之后对目标变量使用
。if (dr.IsNull("FirstName"))
或执行==null
>作为字符串I believe, the data cell beeing null cannot be the reason for your problem. Maybe the column doesn't exist, or any other error happened, or the DataRow itself is null and you should handle that. Look at the exception - "seems to blow up" is not a valid description of your problem.
The following explains that, but will also answer the question from the title for everyone else.
If the column value is null, an object
System.DBNull
is returned, and.ToString()
returns an empty string, while(string)
oras string
returnnull
.So it makes no sense to check the returned item for
==null
because that won't ever evaluate totrue
.DBNull
case.null
, change.ToString()
toas string
.if (dr.IsNull("FirstName"))
or do==null
on the target variable after theas string
.dr["FirstName"].ToString()
有时会抛出空指针异常,因为您尝试访问空对象上的ToString
。除此之外,字符串可以为空,所以实际上,如果您知道它是一个字符串,并且不介意它为空,那么这样做是安全的dr["FirstName"].ToString()
will occasionally throw null pointer exceptions because you're trying to accessToString
on a null object. Other than that, strings can be null, so really, if you know it's a string, and you don't mind that it's null, it'd be safe to do将列和默认值传递给辅助函数,该函数检查是否为 null,如果为 null,则返回默认值;如果不为 null,则返回列值。
Pass the column, and a default value to a helper function that checks for null and returns the default if null, or the column value if not null.
如果列为空,您可以使用以下命令返回空字符串。
You can use the following to return a blank string if the column is null.