Search code examples
c#databasewindows-phone-7observablecollection

InvalidCastException when adding new item to table


I am trying to add a new item to a table however the below code is throwing an InvalidCastException.

This is from the add item page to add a new item into my table. The WineDate is coming from a DatePicker, WineStars from a ListPicker, and Category is coming from a listpicker linked to a table

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

            };

please let me know if you need any further information to help me.


Solution

  • You are only performing two casts: You're casting StarList.SelectedItem to a string and you're casting winecategoriesListPicker.SelectedItem to a WineCategory. You should attach the debugger and view what these values actually are to determine what you're doing wrong.

    (This assumes that none of the property setters in WineItem perform casting, but I'm going for the obvious solution first.)