I'm trying to pull some data from my Database, but when it comes to Datetime
I get an
InvalidCastException
This is my Database (SQL SERVER)
Create table Timeline(
start date,
end date
)
table Timeline
start(date) end(date)
03/07/2020 NULL
NULL 10/07/2020
15/07/2020 25/07/2020
This is my query
SELECT Timeline.start, Timeline.end FROM Timeline
This is my c# code
public class Timeline
{
public DateTime? startDate;
public DateTime? endDate;
public static Timeline fromRow(DataRow r)
{
Timeline a = new Timeline();
a.startDate = r.Field<DateTime?>("start");
a.endDate = r.Field<DateTime?>("end");
return a;
}
}
When I pull a NULL
value it works, but when I pull a real date like 03/07/2020
It gives me InvalidCastException . Is there a way to check the value before putting it into the variable?
This is because the column type does not match up with what you are trying to cast to here, my guess is it is being referenced as a varchar type constructor public DataColumn (string columnName) , which is fine we can just parse the date safely as a string, you may lose a few cycles on this but this is not 1995 anymore. If you want to cast safely than offer the column the correct type so constructor public DataColumn (string columnName, Type type)
// Change Names to match C# nameing conventions
public class TimeLine
{
// Since this class is just a strongly typed object for rows of your table values should not be able to change.
public DateTime? StartDate { get; private set; }
public DateTime? EndDate { get; private set; }
public static TimeLine FromRow(DataRow r)
{
// Casting will depend if we know the DataColumns type, if we dont we can just parse the string value
return new TimeLine
{
StartDate = DateTime.TryParse(r.Field<string>("start"), out var sd) ? sd : (DateTime?)null,
EndDate = DateTime.TryParse(r.Field<string>("end"), out var ed) ? ed : (DateTime?)null,
};
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.