Vinoth
Vinoth

Reputation: 773

How to save null value to Mysql table DateTime field In C#

I want to save null value for dateTime field if the DateEdit (dev express C# windows application control) editvalue is null.

If dateEdit Control has a edit value it save the selected date.If its is null it save a default date But i want to save Null value if the dateEdit value is null.

SAmple COde: i am using entity frame work,

Orders ord= new Orders();
ord.OrderDate= dateEdit1.DateTime;**//here i want to save null value if the dateEdit control value is null** 
Objcontext.Orders.AddObject(ord);
Objcontext.SaveChanges();

Upvotes: 4

Views: 5691

Answers (5)

Vinoth
Vinoth

Reputation: 773

Orders ord = new Orders();

if(dateEdit1.EditValue!=null)

{ord.OrderDate = dateEdit1.DateTime.Date}

else

{ord.OrderDate= null}

dateEdit control value is null 
Objcontext.Orders.AddObject(ord);
Objcontext.SaveChanges();

Now, I am able to save null value for empty DateTime in the DateEdit.

Upvotes: 0

John Woo
John Woo

Reputation: 263693

are you using ADO Command with Parameters? if so then try something this,

// other codes here
command.AddWithValue("@paramName",  (dateEdit.EditValue == null) ? DBNull.Value : dateEdit.EditValue);

dateEdit Control is a DevExpress component right?

or try

Orders ord = new Orders();
ord.OrderDate = (dateEdit1.DateTime == null ? DBNull.Value : dateEdit1.DateTime); //here i want to save null value if the dateEdit control value is null 
Objcontext.Orders.AddObject(ord);
Objcontext.SaveChanges();

enter image description here

Upvotes: 2

vishnu saini
vishnu saini

Reputation: 66

It may help to store null DateTime for your DateEdit.

DateTime? DateEdit = null;

Upvotes: 0

aiodintsov
aiodintsov

Reputation: 2605

use Nullable type:

DateTime ? nullableDate = GetSomeDate();

this also applies to other value types.

There is also DBNull class that may be helpful in such operations. Use could be like this:

sqlCommand.Parameters.AddWithValue("created",nullableDate??DBNull.Value);

or similar. starting with .NET Framework 4 MS wants us to pass DBNull.Value for null values.

Upvotes: 0

Prasath Albert
Prasath Albert

Reputation: 1457

You should set the Field property as NULL for accepting NULL values. Otherwise it will save like "0000-00-00".

Upvotes: 0

Related Questions