Checking for DBNull throws a StrongTypingException

2020-08-26 03:53发布

I am using a dataset to pull data from a DB. One of the fields in a row is NULL. I know this. However, the following vb.net code throws a StrongTypingException (in the autogenerated get_SomeField() method in the dataset designer):

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

According to documentation and this question it should be fine.

edit: If aRow.SomeField is DBNull.Value Then also returns the same error. Argh.

6条回答
神经病院院长
2楼-- · 2020-08-26 04:32

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
查看更多
闹够了就滚
3楼-- · 2020-08-26 04:41

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.

查看更多
干净又极端
4楼-- · 2020-08-26 04:41

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

查看更多
神经病院院长
5楼-- · 2020-08-26 04:47

Try this: aRow.IsSomeFieldNull

查看更多
6楼-- · 2020-08-26 04:49

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

查看更多
地球回转人心会变
7楼-- · 2020-08-26 04:53
**DateTime? ToDate = (row.IsToDateNull()) ? null : row.IsToDate;**
查看更多
登录 后发表回答