How to do Conditional check Date should not be blank in C#? - c#

I have a date model ( project.CreateDate ) in my c# project, how do i can conditionally check that Date is not null, like
//i know this can not be applied, because it is type of Date and string
if (project.CreateDate != "" ){
//other process
}
so how do i can check?

If .CreateDate is of type System.Nullable<DateTime> you could easily do the following check:
if (project.CreateDate.HasValue)
or
if (project.CreateDate != null)
and maybe enhance this with
if (project.CreateDate.HasValue && DateTime.MinValue < project.CreateDate.Value)
Otherwise you might go the ugly path eg
if (project.CreateDate != DateTime.MinValue)
or
if (DateTime.MinValue < project.CreateDate)
If .CreateDate is of type System.String you go for
if (!string.IsNullOrEmpty(project.CreateDate))
or with .NET 4.0 and System.String
if (!string.IsNullOrWhiteSpace(project.CreateDate))
I strongly encourage you to use System.Nullable<DateTime> (aka System.DateTime?) to go for the first solution. The value System.DateTime.MinValue might always be a "non-real"-value, but you will lose the possibility of using System.DateTime.MinValue in your application (compare to not be able to use 0 in your application) as a real-value

A DateTime that is not set otherwise to a given date will have a default value of DateTime.MinValue. You can compare against that:
if (project.CreateDate != DateTime.MinValue)
{
// can use date
}
If it is actually a nullable date (Nullable<DateTime> or just DateTime?), the default value will simply be the functional equivalent of null.
if (project.CreateDate != null) // for nullable dates

Date is a value type so if the variable is not declared as nullable, if it is you can use project.CreateDate.HasValue, othwerise you can test it against the default value:
if (project.CreateDate != default(DateTime))
{
}

Related

csharp Value of '01/01/0001 00:00:00' is not valid how to handle?

if (File.Exists(settingsFile))
{
string[] lines = File.ReadAllLines(settingsFile);
if (lines.Length > 0)
{
trackBarHours.Value = Convert.ToInt32(optionsfile.GetKey("trackbarhours"));
trackBarMinutes.Value = Convert.ToInt32(optionsfile.GetKey("trackbarminutes"));
trackBarSeconds.Value = Convert.ToInt32(optionsfile.GetKey("trackbarseconds"));
savedMilliseconds = Convert.ToInt32(optionsfile.GetKey("milliseconds"));
dateTimePicker1.Value = Convert.ToDateTime(optionsfile.GetKey("timetargetvalue"));
richTextBox1.Text = optionsfile.GetKey("result");
}
}
because the key "timetargetvalue" is not yet created in the settingsFile because i didn't saved it yet for the first time the value of the key of "timetargetvalue" is '01/01/0001 00:00:00'
in that case that there is no yet the key hwo can i handle the datetime exception ?
dateTimePicker1 is a DateTimePicker control.
the exception is on the line :
dateTimePicker1.Value = Convert.ToDateTime(optionsfile.GetKey("timetargetvalue"));
System.ArgumentOutOfRangeException: 'Value of '01/01/0001 00:00:00' is not valid for 'Value'. 'Value' should be between 'MinDate' and 'MaxDate'.
Parameter name: Value'
what should i check against of so it will not throw the exception ?
DateTimePicker.Value must be above DateTimePicker.MinimumDateTime, which is 'January 1, 1753'.
When you haven't set the timetargetvalue, it will resolve to '01/01/0001 00:00:00', as you have seen, which is too early.
So you need to check the value before assigning it to DateTimePicker.Value.
You can do it like this:
DateTime tempDateTime = Convert.ToDateTime(optionsfile.GetKey("timetargetvalue");
dateTimePicker1.Value = tempDateTime >= DateTimePicker.MinimumDateTime ? tempDateTime : DateTimePicker.MinimumDateTime;
When dealing with a Struct such as DateTime that does not have any value we need to consider that this is not a class and can not be set to null. It must always have some value. (see https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=net-7.0)
The exception mentions in a round about way that the range of acceptable values is between dateTimePicker1.MinDate and dateTimePicker1.MaxDate so one option is to check if your value is within this range. But it's unlikely to be the best option. (see https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.datetimepicker.mindate?view=windowsdesktop-6.0)
I'm pretty sure that DateTime default value is equal to that of DateTime.Min but if you really wanted to check if the value is default then I would suggest comparing it to default(DateTime) would be better.
This pretty much covers the use of DateTime and value defaults when null is not an option. Which brings up a possibly more desirable option. Encapsulation.
We could instead encapsulate the DateTime struct into a Nullable class. The encapsulating class will be nullable and will also be able to present the encapsulated value through a property called Value. (see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types)
There are two ways to declare such a Nullable class, both of which compile to the same thing:
Nullable<DateTime> myNullableDate = null;
DateTime? anotherNullableDate = null;
Since the DateTime is encapsulated in a Nullable object we can start using a null reference check. We can also call a method on Nullable called HasValue which returns a bool (True if it has a value).
EDIT: I notice that you're not doing any checks before trying to parse the DateTime and then directly setting it into the DateTimePicker.Value which can accept a null value. (although setting null won't clear a previously set value).
As such perhaps what you might want to do is handle the scenario a bit better and then use a DateTime.TryParse() instead. (see https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-7.0)
e.g. (not the most optimized code, but I think it's easier to follow along in a more verbose form)
private DateTime? LoadDateFromOptions(string key)
{
var rawValue = optionsfile.GetKey(key);
if (!string.IsNullOrEmpty(rawValue))
{
return null;
}
DateTime dateValue;
bool isSuccess = DateTime.TryParse(rawValue, out dateValue);
if (isSuccess)
{
return dateValue;
}
else
{
return null;
}
}
and then instead of having that exception you can load the value optionally a bit more like this:
var timeTarget = LoadDateFromOptions("timetargetvalue");
if (timeTarget != null)
{
dateTimePicker1.Value = timeTarget;
}

Allow null DateTime? variable comparison with DateTime variable in C#

I have two variables of type DateTime and DateTime?
DateTime StartDateFromDb;
DateTime? StartDateFromFilter;
if(StartDateFromDb.Date == StartDateFromFilter.Date);
While comparing, .Date is not allowingfor StartDateFromFilter of type allow null
Thanks in advance
Use the Value property available as
if(StartDateFromFilter.HasValue && StartDateFromDb.Date == StartDateFromFilter.Value.Date)
PS: Better to add a null value check. StartDateFromFilter must have a value.(HasValue is true when DateTime? type variable is not null)
For any nullable type , you can use value property.
StartDateFromFilter.Value.Date
In your case , this should work fine
if(StartDateFromDb.Date == StartDateFromFilter.Value.Date)
//// in this case .Date is not allowingfor StartDateFromFilter

Excel Import Data Parse Error Of Internationaly Formatted Numbers

I'm importing an excel file and i want to add the values to a database. in the database there is a type decimal(18, 5) and i want to add my value 0.00204 to that column in the database. My variable in my model class is of type decimal and i'm trying this code:
Convert.ToDecimal(items[7]);
but then i get the error that the input if not correct format.
items is of type object[]. How do i parse the value into a decimal?
all the others work just fine:
product.packSize = Convert.ToInt32(items[3]);
product.leadTime = Convert.ToString(items[4]);
product.generalAccessoryCategoryId = Convert.ToInt32(items[5]);
product.Company = Convert.ToString(items[6]);
product.Weight = Convert.ToDecimal(items[7]);
Check for the possible error conditions which may exist at any stage then once safe, extract the string:
decimal result;
if ((items!= null) &&
(items.Any()) &&
(items[7] != null) &&
(Decimal.TryParse(items[7].ToString(), out result))
product.Weight = result;
After a couple of comments and some investigation, I believe that the items[7] has characters which the convert is not expecting. I have updated my answer above.
decimal result;
Decimal.TryParse("0a00204", out result); // Returns false
EDIT
If you are dealing with a culture issue, you can use this TryParse(Object, NumberStyles, IFormatProvider, out decimal) and include your culture (using en-GB as an example):
decimal.TryParse(items[7], NumberStyles.Any, CultureInfo.GetCultureInfo("en-GB"), out product.Weight);
If the item variables have default values, you can use TryParse which will replace the value if it can be parsed, or leave it as the default. Otherwise you can use the result from TryParse (true if it succeeds, false if it fails) to determine whether you need to set the value. For example:
decimal.TryParse(items[7], out product.Weight)
OR
if(!decimal.TryParse(items[7], out product.Weight))
{
product.Weight = (decimal)0;
}
It may also help to call the ToString() method on the object in the array, as sometimes the parse function can have more trouble with interpreting objects than their String reprentations.
if(items != null && items[7] != null){
product.Weight = decimal.Parse(items[7].ToString());
}

How can someone handle default datetime

I have DAL where I convert database null value to their equivalent representation in C#. For example:
NULL for Numeric = 0
NULL for String = String.Empty
NULL for DateTime = "1/1/0001" (i.e. DateTime.MinValue)
The problem, for date, lies in the presentation layer, especially in GridViews. You cannot show 1/1/01 to users.
What I used to do is check if myDate.Year=1 or myDate.Year < AcceptedDate and display empty string, but seems to be extra effort unlike other types
Please am open to better approach. Thanks.
Use Nullable datatype to store null value.
DateTime? value = null;
int? myNullableInt = 1;
value = DateTime.Now;
How to check whether variable has value or null
if (value!=null)
String value can store null, so there is no diffrent datatype for string to store null.
string var;
if (var == null)
or
if (String.IsNullOrEmpty(var))
You can also use DateTime.MinValue constant.
http://msdn.microsoft.com/en-us/library/system.datetime.minvalue.aspx
Your conditions would be:
if (myDate == DateTime.MinValue)
You can use Nullable DateTime, so you will return DateTime? instead of DateTime from your DAL. This way you can check if returned value is null.
DateTime? dateTime = null;
As the others mention, you could use a System::Nullable<DateTime>.
The other approach I've seen is to use a standard DateTime and just use a special value such as DateTime.MinValue. This is useful if you need to honor an existing interface's types and can't change the DateTime to a Nullable<DateTime>.
You can either use a Nullable DateTime as the others suggested, or use this trick:
(To prevent non valid defaults.)
// If dateTime has not been initialize, initialize to Now
// (or to any other legal inital values)
dateTime = ((dateTime != new DateTime()) ? dateTime : DateTime.Now);
This trick is useful if you have to use a non-nullable DateTime and want to provide a default if none. (E.g. you have a non-nullable DateTime column in a DB and want to set the value only if row is new.)
I don't think you have much choice but to make the check like you have been and display accordingly. A nullable type might make things easier for you. Depending on your data, even the numeric should be treated this way. DBNull != 0.

DateTime as empty String or null ?How to check?

Q:
I want to check the DateTime against null value to empty the cell in my report if the datetime is null.but i don't know how to do this :it appears like this 1/1/0001 if it was null.and i want it to be empty cell.
This is the datatype in my dataset :
and this is the expression value of my column :
=FormatDateTime(Fields!D_DateTime.Value,2)
As I told you in my comment, you should check if your date is DateTime.MinValue (the minimum value a date can assume, which is exactly 01/01/0001).
if (your_date_property == DateTime.MinValue)
{
// Do what you need
}
=IIf(FormatDateTime(Fields!D_DateTime.Value,2)=CDate("1/1/0001"),"",FormatDateTime(Fields!D_DateTime.Value,2))
Thanks a lot ,i think this fixes my problem.
As datetime is a struct rather than class i.e. a value type rather than a reference type; it must be initialized with some value. It cannot have null values.
Hence to check the default value you should check the equality with DateTime.MinValue
i.e.
if(D_DateTime.Value == DateTime.MinValue)
{
//write code here for default value handling
}
Change the type of the field in the dataset (rd:TypeName) to System.Nullable (Of System.DateTime). Then you can simply test =Fields!D_DateTime.Value Is Nothing.
Like #Marco suggested you can check for MinValue. And if you want to pass NULL to the nullable parameter, you can use the following code for reportviewer parameter.
Vb.Net
Dim rpFrom As New ReportParameter("FromDate", New String() {Nothing}, False)
C#
ReportParameter rpFrom = new ReportParameter("FromDate", new string[] { null }, false);

Categories

Resources