c# - Unable to cast object of type 'System.DateTime' to type 'System.String' -
getting error has me stumped. i'm assuming it's simple can't seem figure 1 out, code causing error:
if ((string) _nullabledatetimepicker1.value != string.empty && _nullabledatetimepicker1.value != null) { _nullabledatetimepicker1.value = null; }
when clicking on search button in windows form, popping up:
unable cast object of type 'system.datetime' type 'system.string'.
it appears type of nullable-type instance of _nullabledatetimepicker1
datetime
, not string; need compare datetime
or convert string.
so, in simplest sense:
_nullabledatetimepicker1.value.tostring() != string.empty
however, beware danger of not checking hasvalue
, cause nullreferenceexception
if value
null
; so, check little backwards.
and then, if wasn't null
, you'd have datetime.minvalue
, , tostring
wouldn't return empty string. therefore, check null
on nullable thing, , if not null
, compare datetime.minvalue
(unless there's quirk in code means have different 'default'.