I am storing date as string in sql table. If date is not passed then it will be null. Now I want to check whether date is null from the design page of asp.net. I am getting error of type cast. Any one is having idea how to overcome this?
<%# ((DateTime)Eval("Date")).ToString("yyy-MM-dd hh:mm tt") %>">
Here data is getting as string input.
Thanks
I am storing date as string in SQL table.
This is your first problem ( here is a good explanation of why this is a problem ).
I am getting error of type cast.
This is how your first problem (storing a date as a string) causes your second problem (type cast error). Although it is possible to fix this by parsing the date from a string
using DateTime.Parse
, DateTime.ParseExact
, or DateTime.TryParse
, I would strongly recommend against using any of these approaches.
The good news is that once you fix the first problem, the second problem goes away by itself!
Use this approach to change the type of the column without losing the data:
date
to your table date
column from the old varchar
column that contains string representations of dates varchar
column Your result variable must be of nullable type (you can not assign null
to DateTime
). Use DateTime.TryParseExact() . If parsing fails, assign null
, else assign the parsed value.
As DavidG noted, this is a hack , actually you should store dates as datetime or datetime2 SQL type!
using System.Globalization;
const string format = "yyyy-MM-dd hh:mm tt";
CultureInfo enUS = new CultureInfo("en-US");
string dateString = Eval("Date"); // e.g. "2017-11-13 02:16 PM"
DateTime? result; // final result or null stored here
DateTime parseResult;
if (DateTime.TryParseExact(dateString, format, enUS, DateTimeStyles.None, out parseResult)) {
result = parseResult;
}
else {
result = null;
}
// check for null before displaying
string display = result.HasValue ? result.Value.ToString(format) : "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.