向表中添加新项时出现InvalidCastException

时间:2013-01-20 23:29:31

标签: c# database windows-phone-7 observablecollection

我正在尝试向表中添加新项,但下面的代码抛出了InvalidCastException。

这是从添加项目页面向我的表中添加新项目。 WineDate来自DatePicker,来自ListPicker的WineStars,而Category来自链接到表的listpicker

WineItem newWineItem = new WineItem
            {
                WineDate = wineDatepurchasedTextbox.Value.Value.Date,
                WineComments = wineCommentsTextBox.Text,
                WineStars = (string)StarList.SelectedItem,
                WineType = wineTypeTextbox.Text,
                WineVinyard = wineVineyardTextbox.Text,
                WineYear = wineYearTextbox.Text,
                Category = (WineCategory)winecategoriesListPicker.SelectedItem

            };

如果您需要任何进一步的信息来帮助我,请告诉我。

2 个答案:

答案 0 :(得分:2)

您只执行两次演员表演:您正在将StarList.SelectedItem投射到string并将winecategoriesListPicker.SelectedItem投射到WineCategory。您应该附加调试器并查看实际这些值是什么,以确定您做错了什么。

(这假设WineItem中没有任何属性设置器执行转换,但我首先要寻找明显的解决方案。)

答案 1 :(得分:0)

Category = (WineCategory)winecategoriesListPicker.SelectedItem

如果winecategoriesListPicker.SelectedItem是继承WineCategory的类,则可以执行此操作,否则必须声明此类或创建接受winecategoriesListPicker.SelectedItem类型的构造函数:

Category = new WineCategory(winecategoriesListPicker.SelectedItem);