Casting Combobox.SelectedItem back to DateTime causes "Specified cast is not valid."
I have the following code which appears correctly populates a combobox
class Hour
{
public string shownHour {get;set;}
public DateTime atime {开发者_如何学Goget;set;}
}
(...)
DateTime now = new DateTime();
now = 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 the "8:00 AM" and "8:30 AM" correctly populate and selectable in the combobox. However, when I attempt to retrieve the ValueMember in the ComboBox_SelectedIndexChanged event I'm getting a "Specified cast is not valid." error. I can't seem to retrieve it back with the following code.
DateTime StartTime = (DateTime) comboBox1.SelectedItem;
In the debugger, I'm seeing the atime from the combobox.SelectedItem and it does appears to be formatted as a DateTime type but I can't seem to cast it back. Am I approaching this problem incorrectly?
Solution: as @Cj S pointed out below, Combobox.SelectedItem was returning the Hour type where I thought it would be returning data of Hour.atime of type DateTime. Using the solution given gave the correct information.
You can't cast a string to a DateTime. Use DateTime.Parse instead.
If your combo is DataBinded then you need to do the following.
int intId = ((Priority)comboPriority.SelectedValue).Id;
Where Priority
is my Entity Class
Oops...
I was completely wrong. You need to get the SelectedValue
instead of the SelectedItem
like this:
DateTime StartTime = (DateTime) comboBox1.SelectedValue;
I believe that your selected item is the of the type Hour
and you are trying to cast it as a DateTime
I believe your code should be somethign like
DateTime StartTime = (DateTime) comboBox1.SelectedItem.atime;
精彩评论