How to store a null value in a Mysql table DateTime field In C #

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

If the value of the dateEdit Control parameter has an editing value, it saves the selected date. If it is null, it saves the default date. But I want to keep Null if dateEdit is null.

SAmple COde: I use object 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(); 
+4
source share
5 answers

Are you using ADO Command with Parameters ? if so, try something like this,

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

dateEdit Control DevExpress component on the 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

+2
source

You must set the Field property to NULL to accept NULL values. Otherwise, it will be saved as "0000-00-00".

0
source

use the nullable type:

 DateTime ? nullableDate = GetSomeDate(); 

this also applies to other types of values.

There is also a DBNull class that can be useful in such operations. Use may be as follows:

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

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

0
source

This can help keep null DateTime for your DateEdit.

 DateTime? DateEdit = null; 
0
source
 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 can save a null value for an empty DateTime in DateEdit .

0
source

Source: https://habr.com/ru/post/1432874/


All Articles