How to save null value to Mysql table DateTime field In C# - 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();

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();

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

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.

It may help to store null DateTime for your DateEdit.
DateTime? DateEdit = null;

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.

Related

assigning to list variable datatable object datetime

item["firstTime"] is DateTime object which may be NULL
If I use this:
firstDate= Convert.ToDateTime(item["firstTime"].ToString()),
while dataobject has some data inside everything is OK.
But if dataobject is NULL then I have error.
I've tried this but it won't help :(
firstDate= Convert.ToDateTime(string.IsNullOrEmpty(item["firstTime"].ToString()) ?
"NULL" : item["firstTime"].ToString()),
Because of your title i guess item is a DataRow. I don't understand why you convert the object to a string when it actually should be (and probably already is) a DateTime.
You should try this, if it works it's the best approach:
DateTime? firstDate = item.Field<DateTime?>("firstTime");
Field is an extension method that supports nullable types. So if the DataTable's column is actually a DateTime-column but it contains DbNull then this will assign a DateTime? to the variable.
If you want the string NULL in case it is null:
string result = firstDate?.ToString() ?? "NULL";

How to handle SQL Server NULL values

I'm trying to get values from my database, it works when all columns have values. When a value is NULL, it returns an error.
I've managed to find a way to handle with the strings but if there's an integer I don't know how to handle it. I've tried to find a solution but none has worked for me so far! Here's the code, any help would be highly appreciated.
Thanks!
while (dr.Read())
{
coments comentsar = new coments
{
Id = (int)dr["Id"],
Name = (string)dr["Name"],
Likes = (int)dr["Likes"],
// Signature = dr["Signature"].ToString(),
Datetime = (DateTime)dr["Datetime"]
};
comen.Add(comentsar);
return comen;
}
You can check for null value and if the value is not null assign the variable using ternary operator:
Signature = dr["Signature"] != DBNull.Value ? (string)dr["Signature"] : "No value",
Likes = dr["Likes"] != DBNull.Value ? Convert.ToInt32(dr["Likes"]) : 0,
You need to change your types to Nullable types.
Change (int)dr["Likes"] to (int?)dr["Likes"]
and Datetime = (DateTime)dr["Datetime"] to Datetime = (DateTime?)dr["Datetime"].
You will also need to update your model coments to allow for nullable types.
Microsoft Nullable Types.

Lightswitch NullReferenceException for String in C#

I am sure this is a case of basic ignorance, but I'm trying to test a database value using code behind in a Lightswitch project.
I'm checking if a varchar(MAX) value is null
if (Order.OrderNotes.Equals(null))
{
do.something...
}
However, I get a NullReferenceException if the value is null. If a value is there I get no error. I've tried using .contains(null), .Length = 0, .ToString() = "" etc without luck. It seems that ints and dates work fine using Equals(null), but not it seems for a string.
Help!!
Assuming you're calling this from a details screen where Order != null as #DeeMac pointed out.
You can check that Order isn't null using the same code below :
if (Order.OrderNotes == null)
{
// do.something...
}
if OrderNotes is null, you can't call any method, properties or whatever using that instance
you should call
if (Order.OrderNotes == null)
of course I assume that the var Order is not itself null,
if you want to be absolutely sure you could change your test in this way
if (Order != null && Order.OrderNotes == null)
In LightSwitch, to test if a nullable property has a value or not, you can use HasValue, so:
"if Order.OrderNotes.HasValue"
If you want the value if there is one, or the default value for the property type, you can use GetValueOrDefault:
"var value = Order.OrderNotes.GetValueOrDefault"
I agree wholeheartedly with Steve that you should be doing null checking on objects (such as Order) before trying to get a value from any of that object's properties.

What is standard way to handle Null dates in .NET

I have asp.net form with C#, where is I am taking user information to insert in the database as usual by using Linq. well. Where as I am taking Date of birth also from the user, but if user skip to fill date text box from ui, then I am getting date like '01/01/0001' something like this, which certainly database security would not allow to store it.
So I need to check somewhere in my code that it is null or in this (above given) format. If it is null or in format '01/01/0001' then what exactly I have to do? I don't have any default
value for dates.
So what is the standard way to handle if date is null (but not mandatory).Please guide me. So many times I found myself in trap while handling null for various types.
Edited
see what i did seems it working here. but i don't think so this is standard way:
DateTime? otxtDOB = new DateTime();
if (!string.IsNullOrEmpty(DOB))
{
if (Convert.ToDateTime(DOB) != DateTime.MinValue)
{
otxtDateOfPurchese = Convert.ToDateTime(Convert.ToDateTime(DOB).ToString("dd-MMM-yyyy"));
}
else
{
otxtDOB = null;
}
}
Please confirm me is this right way ?
Making the date property Nullable (i.e. a "DateTime?") should allow it to actually be null if the user hasn't set it. (And provided your database column will allow nulls, it can be stored as null in the database)
Otherwise it's going to default to DateTime.MinValue which is what you're seeing here. And you'll have to explicity test for DateTime.MinValue when adding to the database.
DateTime is a value type (like a number), so you can't assing a null value to it. Mane people use DateTime.MinValue or DateTime.MaxValue instead, but I prefer to use nullable types:
DateTime? nullableDate;
dateSample.Value = null;
you can do some thing like this C# have some features like nullable type you can make use of
this it will save you some piece of code it will be more robust too.
Public int InsertData(int? ouId)
{
chkValue = ouId.HasValue ? ouId.Value : 0;
}
You have the option of using Nullable<DateTime> (alias DateTime?). This makes you able to handle the date as null throughout your application.
However, personally I am not to found of nullables and would prefer this second path: You can use DateTime.MinValue (which is 01/01/0001) as a meaningful constant in your application and the check for DateTime.MinValue in your data access layer.
The database, if it is an SQL Server and the field is of type smalldatetime, would overflow and throw an exception if you tried to save DateTime.MinValue. Null however, may well be stored in the database for any type.
This is how you can parse your strings into nullable types:
private delegate bool TryParseDelegate<T>(string s, out T t);
private static T? TryParseNullable<T>(string s, TryParseDelegate<T> tryParse) where T : struct
{
if (string.IsNullOrEmpty(s))
return null;
T t;
if(tryParse(s, out t))
return t;
return null;
}
with usage:
var nullableDateTime = TryParseNullable<DateTime>("01/01/0001", DateTime.TryParse);
use
DateTime dt;
if(DateTime.TryParse(DatetImeValue.Tostring(),dt)) // datetimevalue is your db value
{
datetimeproperty = dt; // in your class declare it as DateTime? datetimeproperty
}
else
{
datetimeproperty = null;
}
While displaying check for null, if its null set it empty.
[Update]
Do one thing, Keep the property nullable. In your database. Set field to allow null and in the parameter user #DateTimeParam = null.
OR A QUICK WORKAROUND MAKE THE DATABASE FIELD AND PARAMETER VARCHAR INSTEAD OF DATETIME, IN PARAMETER PASS DATETIMEVALUE.TOSHORTDATESTRING() AND ALSO CHECK IF USER SKIPS
PUT STRING.EMPTY IN PARAMETER. IN THIS MANNER IT WILL BE EASY TO YOU TO DISPLAY DATE AND TIME. YOU NEED NOT CAST OR WIPE OFF THE TIME PART IF YOU DO NOT NEED IT
obj.BirthDate = Convert.ToDateTime(string.IsNullOrEmpty(txtBirthDate.Text.ToString()) ? System.Data.SqlTypes.SqlDateTime.MinValue.Value : Convert.ToDateTime(txtBirthDate.Text.ToString()));
You can use this while passing to database.
object datetimeObj = null;
if (datetimefromUI == DateTime.MinValue) // This is put in the DateTime object by default
datetimeObj = DBNull.Value;
else
datetimeObj = datetimefromUI;
// Post datetimeObj to parameter in database...

insert null value when no selected value from ddl

I had ddl which determine gender and user can donot choose any value from ddl so i tried to check if user didnot select any value from ddl inser null value or any value in database i made that but error apear(Procedure or Function 'InsertRegisteration' expects parameter '#Gender_Id', which was not supplied).any one help me
(My Code)
if (DDLGender.SelectedItem.Value[0]!= null )
{
command.Parameters.Add("#Gender_Id",SqlDbType.Int).Value=null;
}
else
{
command.Parameters.Add(Parameter.NewInt("#Gender_Id", DDLGender.SelectedValue));
}
Try this:
if (DDLGender.SelectedItem.Value[0]!= null )
{
command.Parameters.Add("#Gender_Id",SqlDbType.Int).Value= DBNull.Value;
}
else
{
command.Parameters.Add(Parameter.NewInt("#Gender_Id", DDLGender.SelectedValue));
}
Added : Difference between null and System.DbNull.Value
Well, null is not an instance of any type. Rather, it is an invalid reference.
However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.
*We would normally say null, but I don't want to confound the issue.
So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).
Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.
Try this:
if (DDLGender.SelectedIndex == 0 )
{
command.Parameters.Add("#Gender_Id", DBNull.Value);
}
else
{
command.Parameters.Add("#Gender_Id", (int)DDLGender.SelectedValue);
}
You don't have to specify the data type for parameters.
Assuming you are using stored procedure for updating,
I think you can make the change in stored procedure to have default value to this INT column as NULL which will make this parameter optional. Then you can execute only the ELSE part here from code.
You can combine the above lines of code to :
cmd.Parameters.Add(new SqlParameter { SqlDbType = SqlDbType.Int, Value = DDLGender.SelectedIndex!=0 ? (int)DDLGender.SelectedValue : null });
The use of Null coalescing operator will do the null check. If the selectedItem is not null then that will be passed in as value otherwise null will be passed.

Categories