[ACCEPTED]-Dataset allowing Null values even when AllowDBNull = False?-strongly-typed-dataset

Accepted answer
Score: 14

The short answer is:

System.DBNull.Value != null

The longer answer is:

In C#, the concept of a NULL value in SQL is 13 represented by the Value property of the System.DBNull class. When 12 dealing with a database, the more familiar 11 C# null doesn't actually mean "null value."

When 10 you set a database column to null, ADO.NET will 9 initialize the column to whatever the default 8 value is for that column (for example, an 7 int column would be initialized to 0). That 6 is, using null can actually cause a non-null 5 value to end up in the database, and therefore 4 you won't get an error.

If you instead set 3 a database column to System.DBNull.Value, the column will actually 2 be set to NULL. This is the situation that AllowDBNulls == false will 1 prevent you from doing.

Score: 2

Regarding your "bonus" ;-) question: NULL 9 (no string) and "" (empty string) are two 8 different things. So it's perfectly reasonable 7 to treat them differently. It's the distinction 6 between null and DBNull that is messing 5 things up. If nullable types had been available 4 at the time of designing ADO.NET, things 3 probably would be a lot easier. But before 2 .NET 2.0, there was no way to represent 1 e.g. a "null integer".

Score: 0

Are you exactly assigning NULL values or 13 an empty string to those columns? If you 12 don't assign any value to a column, it will 11 default to NULL (if a DEFAULT constraint 10 is not imposed). Else you can assign a NULL 9 value by doing -

ds.Tables[0].Rows[0]["Col"] = null;

If you are assigning an 8 Empty string to those columns, it's not 7 equal to NULL.

And if you have a NULL value 6 in a column which has been marked as NOT 5 NULLABLE, it will throw an error -

Column 4 'Col1' does not allow nulls.


By NOT 3 NULLABLE, I mean AllowDBNull = false.

Your 2 code seems correct. Can you try trimming 1 the text?

Here's the whole code -

DataTable dt = new DataTable();

DataColumn column = new DataColumn("Col1");
column.AllowDBNull = false;

DataRow dr = dt.NewRow();
dr["Col1"] = null;


More Related questions