Reputation: 69
I want to compare cell(Datetime) value to empty or "None".If it is not empty or none then after it will add the parameter.I would greatly appreciate of your help.
Thanks,It gives me can't convert date time to string error
command.Parameters.AddWithValue("@pin", row.Cell(2).GetValue<string>());
command.Parameters.AddWithValue("@Amount", row.Cell(3).GetValue<int>());
if(row.Cell(4).GetValue<DateTime>() == "" || row.Cell(4).GetValue<DateTime>() =="none")
{
}
command.Parameters.AddWithValue("@Expirydate", row.Cell(4).GetValue<DateTime>());
command.ExecuteNonQuery();
Upvotes: 1
Views: 1006
Reputation: 52280
Read it as a string first, check it, then convert it to a DateTime.
var s = row.Cell(4).GetValue<String>();
is (s != null && s != "" && s != "none")
{
var d = DateTime.Parse(s);
command.Parameters.AddWithValue("@Expirydate", d);
}
Or rethink the problem. Instead of relying on a magic number, just populate the expiration date whenever it is a valid date, like so:
var s = row.Cell(4).GetValue<String>();
DateTime d;
if (DateTime.TryParse(s, out d))
{
command.Parameters.AddWithValue("@Expirydate", d);
}
Since "none" and "" are not valid dates, this will work, and in addition it will continue to work if someone puts in "None", "N/A", "Never", etc.
Upvotes: 0
Reputation: 125
You can convert DateTime and comapre with a string by parsing as follows
(DateTime.Parse(date).ToString()=="None" || DateTime.Parse(date).ToString()==String.Empty())?true:False
Or you can use a try catch block to validate it.
Upvotes: 1