问题
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.
回答1:
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).
回答2:
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:
Try this: aRow.IsSomeFieldNull
回答4:
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.
回答5:
**DateTime? ToDate = (row.IsToDateNull()) ? null : row.IsToDate;**
回答6:
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
来源:https://stackoverflow.com/questions/4689620/checking-for-dbnull-throws-a-strongtypingexception