Checking for DBNull throws a StrongTypingException

隐身守侯 提交于 2019-12-05 03:36:21

The difference is that in the related question it is talking about an untyped value (i.e. object) via an indexer. When you go via .SomeField, the type is already included - so this could be int etc. And it wouldn't make sense to try IsDBNull on an int, as an int can never be DBNull.

Essentially the SomeField is a wrapper for (excuse the C# accent...)

public int SomeField {
    get { return (int) this["someFieldName"]; }
    set { this["someFieldName"] = value; }
}

I'm not a huge DataTable person, but you could try checking it by name/index/column; or marking the column as nullable so that it is Nullable<int> (in the example above).

Just some additional information: The exception comes because you are using a strongly typed DataSet. StrongTypingException documentation says it:

The exception that is thrown by a strongly typed DataSet when the user accesses a DBNull value.

The usage of strongly typed DataSets is slightly different from that of the untyped ones. With strongly typed DataSets you get automatically some extended/additional methods for your fields that you can call. In your case you would very likely have to call:

If Not aRow.IsSomeFieldNull Then
   'do something
End If

Try this: aRow.IsSomeFieldNull

There is a neat way of going around it. But you need to be aware of consequences.

To prevent exception of occuring you can change in DataSet field property NullValue to either "Null" or "Empty" (whatever suits your needs). Default is set to "Throw Exception".

For a reference look here: msdn documentation

Good luck.

**DateTime? ToDate = (row.IsToDateNull()) ? null : row.IsToDate;**

This question is old but what i'm adding doesn't seem to be in any of the other answers.

If you use

If Not IsDBNull(aRow.item("SomeField")) Then
    'do something
End If

This will not throw an exception even if you're using a strongly typed dataset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!