ASP.NET - how to assign null value in datatime because its non nullable

Asked By mani on 03-May-12 03:12 AM
hi..any one tell me how to assing null value in datetime variable...and save in datetime field..???
Suchit shah replied to mani on 03-May-12 03:20 AM
To Assign the NULL value to datetime you can be able to use the NULLABLE type for that and then you can able to assign it

Nullable<DateTime> _myDateTime;

will work, you should be able to set it to null

Check for nulls:

if (object.myDateTime != null)

or

if (object.myDateTime.HasValue)


Use its Value property, like so:

DateTime? dt = DateTime.Now; //
DateTime? dt = null;
or whatever
MessageBox.Show(dt.Value.ToString(...));

Suchit shah replied to mani on 03-May-12 03:22 AM
To Assign the NULL value to datetime you can be able to use the NULLABLE type for that and then you can able to assign it

Nullable<DateTime> _myDateTime;

will work, you should be able to set it to null

Check for nulls:

if (object.myDateTime != null)

or

if (object.myDateTime.HasValue)


Use its Value property, like so:

DateTime? dt = DateTime.Now; //
DateTime? dt = null;

or

Check if the value you are inserting is null. If so then insert null value like this.


if ((YourDateTime.Text == "") )
 {
  YourDateTime.Text = DBNull.Value;
 }

Neha Garg replied to mani on 03-May-12 03:23 AM
hi mani,

See the below example:

public int Insert_table(int Id, DateTime? date)

and pass the value "null" to date....
aneesa replied to mani on 03-May-12 03:25 AM
insert into table1  (datecolumn) values (null)
dipa ahuja replied to mani on 03-May-12 03:28 AM
You can use textbox or calender control and get the value as :

DateTime dt= DateTime.Parse(textBox1.Text);

now store this dt variable to databse field