Reputation: 115
I'm trying to get the date of birth of employees from the DataRow
s of the DataTable
, but I'm getting the exception:
String was not recognized as a valid DateTime.
Please help me to get the value of type DateTime
from the DataRow
. The following is the my code.
List employeeList = new List();
foreach (DataRow dr in dt.Rows)
{
DateTime t = DateTime.Now;
employeeObject.EmployeeID = Convert.ToInt64(dr["empId"]);
employeeObject.EmployeeFirstName = Convert.ToString(dr["empFirstName"]);
employeeObject.EmployeeMiddleName = Convert.ToString(dr["empMiddleName"]);
employeeObject.EmployeeLastName = Convert.ToString(dr["emptLastName"]);
employeeObject.EmployeeGenderStr = Convert.ToString(dr["empGender"]);
employeeObject.EmployeeDateOfBirth = Convert.ToDateTime(dr["empDOB"]);
//employeeObject.EmployeeDateOfBirth = DateTime.ParseExact(dr["empDOB"].ToString().Replace(";", " "), "m/d/yyyy hh:mm:ss", CultureInfo.InvariantCulture);// DateTime.Parse(dr["empDOB"].ToString());
// employeeObject.EmployeeDateOfBirth = Convert.ToDateTime(dr["empDOB"].ToString().Replace(";", " "), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat); ;
employeeObject.EmployeeContactno = Convert.ToDouble(dr["empContactNo"]);
employeeObject.EmployeeEmailId = Convert.ToString(dr["empEmailId"]);
employeeObject.EmployeeAddress = Convert.ToString(dr["empAddress"]);
employeeObject.EmployeeDesignation = Convert.ToString(dr["empDesgnation"]);
employeeList.Add(employeeObject);
}
Upvotes: 9
Views: 26997
Reputation: 21
It's a little late, but if someone needs it, try this simple solution.
foreach (DataRow row in dt.Rows)
{
if (row["empDOB"] != DBNull.Value)
item.vytvorena = (DateTime)row["empDOB"];
}
Upvotes: 1
Reputation: 1295
employeeObject.EmployeeDateOfBirth= Convert.ToDateTime(dr["empDOB"]);
Upvotes: 5
Reputation: 18749
You could use:
employeeObject.EmployeeDateOfBirth = dr["empDOB"] != null ?
(DateTime)dr["empDOB"] :
DateTime.MinValue;
This will give you the MinValue
if it's null
.
Upvotes: 3
Reputation: 41
Check for null before binding.
From what I can see, am not seeing any check for null and replacing the null with datetime minValue, unless the check is been done within your DB?. I had a similar problem, and that check resolved it.
if (!string.IsNullOrEmpty(dr["empDOB"]))
{employeeObject.EmployeeDateOfBirth = Convert.ToDateTime(dr["empDOB"]);
} else { DateTime DOB = DateTime.MinValue;}
Upvotes: 1
Reputation: 309
Try this:
employeeObject.EmployeeDateOfBirth = DateTime.ParseExact(dr["empDOB"].toString(),
"d/M/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
Upvotes: 0
Reputation: 2623
Try with this and replace "yyyy-MM-dd" with your desired format.
DateTime.ParseExact(dr["empDOB"].toString(), "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture)
Upvotes: 4