I have designed a dataset using VS2008 dataset designer. In one of the datatables, I have set ‘AllowDBNull’ property of most of the columns to be False. However, still if I create a DataRow containing null values for these columns, this datatable accepts this row, without any error.
Am I not understanding something here? Please advice. Thank you.
Edit Mike Spross’ excellent explanation however, brings forth another question. How do we check text fields if they are System.DBNull? It is surprising that DataSets are not considering a string ” as System.DBNull and throwing an exception. Or is it not?
Edit I think I have found the problem and reason. I am initializing a new row of the DataTable, before filling in the values to that row. While initializing the row, default value for string, ie, ” might be being filled in that column. I think that’s it? Any ideas about this?
The short answer is:
System.DBNull.Value != nullThe longer answer is:
In C#, the concept of a
NULLvalue in SQL is represented by theValueproperty of theSystem.DBNullclass. When dealing with a database, the more familiar C#nulldoesn’t actually mean ‘null value.’When you set a database column to
null, ADO.NET will initialize the column to whatever the default value is for that column (for example, anintcolumn would be initialized to 0). That is, usingnullcan actually cause a non-null value to end up in the database, and therefore you won’t get an error.If you instead set a database column to
System.DBNull.Value, the column will actually be set toNULL. This is the situation thatAllowDBNulls == falsewill prevent you from doing.