If you have worked with strongly typed dataset, it is very likely that you must have faced this annoying exception regularly. The error message will be something like this.
The value for column \'ColumnName\' in table \'TableName\' is DBNull.
With exception type : System.Data.StrongTypingException
Well that's a typical message ain't it ? But interesting part is, if you see the property code in the dataset class it will similar to
get {
try {
return ((global::System.String)(this[this.tableName.Column]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'Column\' in table \'TableName\' is DBNull.", e);
}
}
set {
this[this.TableName.Column] = value;
}
Now from the code you can see that, if you are thinking of comparing the field with Dbnull or null or some value still it will give the error. It is a InvalidCast exception.
There is a simple method to solve this issue, when you use the xsd.exe(or VS IDE) to generate the dataset class give a value for the 'null value'
This is how you do it.
1. Add codegen namespace in the scheme
In the xsd file(schema) add the below line to add the namespace immediately after targetnamespace
xmlns:codegen="urn:schemas-microsoft-com:xml-msprop
2. Add the 'null value' to the elements you want to protect from this error.
for ex :
<xs:element name="Column1" codegen:nullValue="-1" type="xs:string" minOccurs="0" />
The bold attribute sets the nullvalue.
Thats it, then generate your typed dataset, and you will no longer have the weird exception.
If you really dont want to touch the xsd, there is another way of getting rid of this, the dataset class gives a method 'IsColumnNull', use this method in your code to check if its null :)
The above information is extracted from MS KB article
Keep strong typing :)
-Rujith