I want to convert text to datetime but having error.My text box value is in format dd/MM/yyyy
String was not recognized as a valid DateTime.
myFtMaster.GENTRTYDATEFROM =Convert.ToDateTime(txtTreatyPeriodfrom.Text.ToString());
My business object ‘gentrtydatefrom’ datatype is DateTime. Also what is the best way to avoid these type of errors without using a Try catch block.
You either specify a culture that uses that specific format:
or use the
ParseExactmethod:The
ParseExactmethod only accepts that specific format, while theConvert.ToDateTimemethod still allows some variations on the format, and also accepts some other date formats.To catch illegal input, you can use the
TryParseExactmethod: