Search code examples
c#visual-studiodatatableado.netdbnull

How to programmatically set NullValue property of DataColumn of ADO.Net DataTable


I have many new wizard-created DataTables in my project, which I need to extract data from. There are many string columns with dbnull values in these tables, which I want to extract as empty strings.

So I went ahead and changed the NullValue property of each DataColumn with DataType of System.String from (Throw exception) to (Empty) like this:

Modifying the NullValue property of DataColumn in VS 2010

I soon got tired of all the repetitive work, so I tried to set NullValue programmatically in the data layer of my application.

I was, however, unable to even find this property. I even decompiled the code of System.Data.DataColumn and the property NullValue did not seem to exist there. NullValue may be some magic feature of Microsoft.VSDesigner.Data.Design.DataColumnEditor, but that's nothing more than a mere suspicion at the moment.

How can I programmatically achieve the same effect as if I did set NullValue to (Empty) in the property editor)?


Solution

  • To be clear: NullValue is not a property of the DataColumn class. It's a convenience setting of the TableAdapter code generator that can be set for each column. In practice, this means that setting this 'property' controls how the body of the column's property (Public Property () as is generated. If, for example, NullValue is set to (Empty) then a conditional is added to the column property code to check for null and return an empty string. If NullValue is left to (Throw Exception) then this conditional is omitted from the property definition. As such, there really isn't a programmatic way to set this property, since you can't alter the tableadapter code at run time. However, you can create a new property (with a different name, such as MyColumnName_Safe) in a partial class for your TableAdapter that has the behavior you want. Just make sure to call the correct property instead of the autogenerated one in your consuming code