SQL - Insert NULL into DateTime SQL - Insert NULL into DateTime sql sql

SQL - Insert NULL into DateTime


I'm using this pattern and I have no problems with nulls or incompatible text format.

cmd1.Parameters.Add["@InsertDate"].Value = textBox1.Text.AsDBDateTime();// ...public static class DBValueExtensions {    public static object AsDBDateTime(this string s) {        object dateTimeValue;        var str = s;        if ( null != str ) { str = str.Trim(); }        if ( string.IsNullOrEmpty(str) ) {            dateTimeValue = DBNull.Value;        }        else {            dateTimeValue = DateTime.Parse(str);        }        return dateTimeValue;}


You can omit optional parameters entirely, instead of setting them to SqlDateTime.Null.

Having said that, the code should still work. How do you read the database? Some viewers display 1900-01-01 for null. What do you see when you run select * from Tables from SQL Server Management Studio?


I suspect that there is an implicit conversion from DBNull to 0 for your date because DateTime is not nullable by default. This would reproduce the behaviour you are seeing.

lol, having just seen the Addomar's answer, if the column in SSMS is not actually null but in fact zero and you cant change the database schema (sometimes this isnt possible) then the approach below will work...

You could try something like datacolumn datagridview replace specific value to replace the value zero with some different text or a blank string?

But ideally change the column to be nullable with no default and omit the parameter when it should be null.