How to resolve "String was not recognized as a valid DateTime"? - c#

I'm converting a text field into date time and inserting into db. However, when the text field is null, it throws an exception that
String was not recognized as a valid DateTime
This is what I did:
nvpt4Entities db = new nvpt4Entities();
ClassInfo order = new ClassInfo
{
ClassID = classID.Text,
ClassName = className.SelectedItem.Text,
ClassTime = classTime1.Text,
ClassDate = DateTime.ParseExact(classDate1.Text, "MM/dd/yyyy", null),
ClassDay = classDay.SelectedValue,
ClassMonth = classMonth.SelectedValue,
ClassLocation = classLocation.SelectedItem.Text,
ClassNotes= classNotes.Text,
ClassInstructor = classInstructor.SelectedValue,
ClassInstructor1 = classInstructor2.SelectedValue,
ClassInstructor2 = classInstructor3.SelectedValue,
MultiDate2 = DateTime.ParseExact(multidate2.Text, "MM/dd/yyyy", null),
MultiDate3 = DateTime.ParseExact(multidate3.Text, "MM/dd/yyyy", null),
MultiDate4 = DateTime.ParseExact(multidate4.Text, "MM/dd/yyyy", null),
MultiDate5 = DateTime.ParseExact(multidate5.Text, "MM/dd/yyyy", null),
ClassStrength = Convert.ToInt16(classStrength.Text),
ClassProvider = classProvider.SelectedItem.Text,
LocationID = Convert.ToInt16(classLocation.SelectedValue),
ClassCID = Convert.ToInt16(className.SelectedValue),
ProviderID = Convert.ToInt16(classProvider.SelectedValue)
};
So, I want to know how to handle null strings to be converted to datetime while inserting into db

This has nothing to do with the database. Pay attention to the error message and where the exception originates. The only thing of relevance is where the error comes from:
DateTime.ParseExact(__, "MM/dd/yyyy", null)
Replace this with an appropriate method call that handles the "empty/invalid string" case, however is appropriate, or use validation to ensure this step is never reached; DateTime? should be used for nullable columns, a sentinel can be used otherwise. (See Mark Byers' answer for what the contents of said method may look like.)
Happy coding.

If your fields are nullable DateTimes you can use this:
ClassDate = string.IsNullOrEmpty(classDate1.Text) ? (DateTime?)null :
DateTime.ParseExact(classDate1.Text, "MM/dd/yyyy", null),

Related

Unable to cast object of type 'System.DateTime' to type 'System.String'. c#

I'm trying to display the dates and restored it to the Labels = strings,
but I got an error on line list.Add((string)myReader["Date"]);
Here's my code:
con.Open();
myReader = cmdDB.ExecuteReader();
List<string> list = new List<string>();
while (myReader.Read())
{
list.Add((string)myReader["Date"]);
}
string[] strings = list.Select(x => x.ToString()).ToArray();
cartesianChart1.AxisX.Add(new Axis
{
Title = "Date",
Labels = strings
});
cartesianChart1.AxisY.Add(new Axis
{
Title = "Sales",
LabelFormatter = value => value.ToString()
});
Any solution? Thank you! P.S. I'm using LiveCharts and MySQL.
You can try like this
list.Add(myReader["Date"].ToString());
If you want you can also apply formatting to your date in the ToString(dd-MM-yyyy) using Custom Date and Time Format Strings
Do
list.Add(Convert.ToString(myReader["Date"]));
It seems your Datecolumn is not string but a datetime column.
Doing (string)myReader["Date"] tries explicit typecasting on a datetime column to string which is not possible. But Convert.ToString gives the string representation of your value.
Even if the value is null, Convert.ToString(object value) will return null instead of throwing exception like .ToString().
Use
if (Convert.IsDBNull(columnValue))
{
return null;
}
return columnValue;
Ever validate is data is null or emty and return a value
Note: if we have column of type DateTime in DataBase and String in asp.net core/Csharp application
we can convert DateTime to string at store procedure level as
e.g
date_format(ReferralDate, '%d/%m/%Y') as ReferralDate,
Full example of Store procedure
SELECT referralCostsID,
ClientID,
ReferralSource,
date_format(ReferralDate, '%d/%m/%Y') as ReferralDate,
AdCost,
Notes
FROM referralcostssetup

Specified cast is not valid exception

This is my code
var result = (from row1 in table.AsEnumerable()
join row2 in tabelPopup.AsEnumerable()
on row1.Field<string>("CallID") equals
row2.Field<string>("callID")
where row1.Field<string>("Direction") == "I"
select new
{
Agent = row1.Field<string>("Agent"),
StartTime = row1.Field<DateTime>("StartTime"),
Reason = row2.Field<string>("Reason")
});
where table and tablePopup are datatable variables.
I got this exception:
Specified cast is not valid
on this code:
new
{
Agent = row1.Field<string>("Agent"),
StartTime = row1.Field<DateTime>("StartTime"),
Reason = row2.Field<string>("Reason")
}
Make sure your column definitions match the type you're using in row1.field<>. i.e. Agent is string, StartTime is datetime and Reason is string. This is likely due to StartTime not being a datetime type.
Probably StartTime is not from Type DateTime. Because of that you receive this exception. Try to convert it. If this is correct you should convert it to DateTime or just retrieve string value.

String was not recognized as a valid DateTime - Whats wrong?

I have been getting an annoying littler error and cannot for the life of me figure out why it is being cause. I have an xml file where i am storing data, as shown below.
- <EmployeeFinance>
<EmployeeEmploy_Id>5584</EmployeeEmploy_Id>
<EmpPersonal_Id>30358</EmpPersonal_Id>
<No_DaysWorked>30</No_DaysWorked>
<Date_Appointment>17/02/2012</Date_Appointment>
<Date_Employment>02/05/1984</Date_Employment>
<Date_Termination>01/01/0001</Date_Termination>
<Payperiod_StartDate>01/01/2013</Payperiod_StartDate>
<Payperiod_EndDate>31/01/2013</Payperiod_EndDate>
<BatchNumber>38</BatchNumber>
<PAYE_ToDate_Computed>0</PAYE_ToDate_Computed>
<Income_Tax_RateID>0</Income_Tax_RateID>
<NIS_RateID>0</NIS_RateID>
<NIS_weeks_worked>0</NIS_weeks_worked>
</EmployeeFinance>
If you look at the date nodes, Payperiod_StartDate,Payperiod_EndDate, Date_Appointment etc. They all have the same format. Now in my C# code, when i write my query to select from the xml file i get the String was not recognized as a valid DateTime error. WHen i comment out all the other dates and leave start_date, it works. They are the same format , i cant see what i am doing wrong. Please help me.
var context = new SSPModel.sspEntities();
XElement xelement = XElement.Load(GlobalClass.GlobalUrl);
XDocument doc = XDocument.Load(GlobalClass.GlobalUrl);
var query = from nm in xelement.Elements("EmployeeFinance")
select new EmployeeEmploy
{
Employee_Personal_InfoEmp_id = (int)nm.Element("EmpPersonal_Id"),
Substantive_designation = (int)nm.Element("Position_Id"),
Grade_Id = (int)nm.Element("Grade_Id"),
PositionTotal_PtBasic = (double)nm.Element("Sum_AllPosition"),//part of basic
GradeTotal_PtBasic = (double)nm.Element("Sum_AllGrade"), //part of basic
Housing_Allowance = (double)nm.Element("Housing"),
Base_Pay = (double)nm.Element("Base_Pay"),
startDate = (DateTime)nm.Element("Payperiod_StartDate"),
endDate = (DateTime)nm.Element("Payperiod_EndDate"),
Date_of_Appointment = (DateTime)nm.Element("Date_Appointment"),
Date_of_Employment = (DateTime)nm.Element("Date_Employment"),
Termination_date_actual = (DateTime)nm.Element("Date_Termination"),
Base_Pay_Currency = (string)nm.Element("Currency"),
Exchange_rate = (double)nm.Element("Exchange_Rate")
};
var x = query.ToList();
foreach (var xy in x) {
Debug.WriteLine(xy.endDate);
}
Because 17/02/2012 is not a valid date, however, 02/17/2012 is. The date will be parsed as mm/dd/yyyy. One option is to use DateTime.ParseExact to parse a date with the dd as the first set of numbers. e.g.
var startDate = DateTime.ParseExact("17/02/2012", "dd/MM/yyyy", null);
The debugger will show you that nm.Element("Payperiod_EndDate").ToString() gives you a string that includes the xml tags for that element. Try the following instead:
startDate = DateTime.ParseExact(nm.Element("Payperiod_EndDate").Value, "dd/MM/yyyy", null)

Linq to SQL for EntityFramework.Extensions Update() method with ?? operator

I have a method with several optional parameters that then updates the database using a LINQ query. I would like to update the record such that the optional fields are only saved if they were supplied in the method, otherwise the values should persist their old value. E.g.,
If I supply optional field "errorMessage" to my method, the database's corresponding record field should update with that value. If the method value is not supplied then I would like the database's record field to persist its existing content (filled or not). However, when using the ?? operator in my query to apply this logic I get the following error;
The parameterized query '(#p__linq__0 int,#p__update__0 nvarchar(198),#p__update__1 nvarc' expects the parameter '#p__update__1', which was not supplied.
I know enough LINQ to know that this basically means that it's having trouble converting the LINQ to SQL. Likewise, I could get around this by first loading the item, applying the method values to the retrieved object and then saving them but this turns a one-step operation into a 3 step operation. I'm hoping there's a concise elegant solution to this that I'm not aware of. Any ideas?
My code;
public void UpdateInvoiceExport(int quickBooksExportID, bool successful, string failureMessage = null,
int? failureRequestID = null, int? failureStatusCode = null,
string failureSeverity = null)
{
// only update certain details if the export was successful
DateTime? exportDateTime = null;
if (successful)
{
exportDateTime = DateTime.Now;
}
// update the export item
_context.QuickBooksExports.Update(item => item.QuickBooksExportID == quickBooksExportID,
qb => new QuickBooksExport
{
DateTimeExported = exportDateTime,
// the addition of the ?? operators here seems to cause the error
LastFailureMessage = failureMessage ?? qb.LastFailureMessage,
FailureRequestID = failureRequestID ?? qb.FailureRequestID,
FailureStatusCode = failureStatusCode ?? qb.FailureStatusCode,
FailureSeverity = failureSeverity ?? qb.FailureSeverity
});
_context.SaveChanges();
}
I have had this issue before, I had to pull the object out, build it first and then pass it in. This prevents the ?? operator from being in the Linq statement.
public void UpdateInvoiceExport(int quickBooksExportID,
bool successful,
string failureMessage = null,
int? failureRequestID = null,
int? failureStatusCode = null,
string failureSeverity = null)
{
// only update certain details if the export was successful
DateTime? exportDateTime = null;
if (successful)
{
exportDateTime = DateTime.Now;
}
// update the export item
var quickBooksExport = new QuickBooksExport;
{
DateTimeExported = exportDateTime
};
quickBooksExport.LastFailureMessage = failureMessage ?? qb.LastFailureMessage;
quickBooksExport.FailureRequestID = failureRequestID ?? qb.FailureRequestID;
quickBooksExport.FailureStatusCode = failureStatusCode ?? qb.FailureStatusCode;
quickBooksExport.FailureSeverity = failureSeverity ?? qb.FailureSeverity;
_context.QuickBooksExports.Update(item => item.QuickBooksExportID == quickBooksExportID,
qb => quickBooksExport);
_context.SaveChanges();
}

.NET MVC Controller Exception

[HttpPost]
public JsonResult CreateUser(UserCreateDTO dto)
{
Entity.User Us = new User();
Us.Name = dto.Name;
Us.Surname = dto.Surname;
Us.Username = dto.Username;
Us.Password = dto.Password;
container.Users.Add(Us);
container.SaveChanges();
UserCreateList UsList = new UserCreateList
{
Id = Us.Id,
Name = Us.Name,
Surname = Us.Surname,
Username = Us.Username,
Email = Us.Email,
Password = Us.Password
};
return Json(UsList);
}
It's an ajax New Member Form.
When it comes to this controller from ajax submit, it's throwing an internal network server error. I debugged the code and its crashed at the line container.users.add(us); and the line below..
According to my examples it must be Users.AddObject but there's no AddObject selection..
It can be a problem for giving error or how can I fix it.
www.muratkamci.com/exception.jpg
This is the pic of ex.
That error "conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value." can occur when you fail to set a datetime value on a field that does not accept nulls. Since you aren't defining any DateTime properties on your User object, this is a likely scenario. Look at your model, and see if you can find a non-nullable datetime field.

Categories