The techie in me RSS 2.0
 Saturday, May 17, 2008

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

Saturday, May 17, 2008 1:21:57 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
Coding
Comments are closed.
About me
Name : Rujith Anand Send mail to the author(s)
Archive
<September 2010>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789
Blogs I read
Disclaimer

Disclaimer
Postings are provided as is with no warranties, and confer no rights. Opinions expressed here are my own delusions; my employers at best shake their heads and sigh, at worst repudiate the content with extreme prejudice, whenever it manages to appear on their radar.

© Copyright 2010
Rujith Anand

Statistics
Advertisement
All Content © 2010, Rujith Anand