c# - Casting Combobox.SelectedItem back to DateTime causes "Specified cast is not valid." -
i have following code appears correctly populates combobox
class hour { public string shownhour {get;set;} public datetime atime {get;set;} } (...) datetime = new datetime(); = datetime.now; list<hour> hours = new list<hour> { new hour{shownhour = "8:00 am", atime = new datetime(now.year, now.month, now.day, 8,0,0)}, new hour{shownhour = "8:30 am", atime = new datetime(now.year, now.month, now.day, 8,30,0)} }; combobox1.datasource = hours; combobox1.valuemember = "atime"; combobox1.displaymember = "shownhour";
i'm seeing "8:00 am" , "8:30 am" correctly populate , selectable in combobox. however, when attempt retrieve valuemember in combobox_selectedindexchanged event i'm getting "specified cast not valid." error. can't seem retrieve following code.
datetime starttime = (datetime) combobox1.selecteditem;
in debugger, i'm seeing atime combobox.selecteditem , appears formatted datetime type can't seem cast back. approaching problem incorrectly?
solution: @cj s pointed out below, combobox.selecteditem returning hour type thought returning data of hour.atime of type datetime. using solution given gave correct information.
you can't cast string datetime. use datetime.parse instead.
Comments
Post a Comment