Reputation: 1
I am making a pet shop app for windows phone 7 in visual studios 2010. I am trying to get the items from one page that have already been copied to the temporary list in app.xaml (can see this in the debugger) to display in my other list on the basket page but when the button to direct to the basket page is clicked the application crashes. I did not use binding for any part of the app
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
thisApp.petBasket.Add(lstAllPets.SelectedItem as Pets);
MessageBox.Show("Item added to the Basket");
}
this is the code used to add the item to the temporary list
public void ShowBasket()
{
if (thisApp.petBasket != null)
{
//show pets that have been added to the basket
foreach (Pets currpet in thisApp.petBasket)
{
lstBasketItems.Items.Add(currpet.Name + "" + currpet.Gender + "" + currpet.Dob + "" + currpet.Category + "");
}
}
}
this is the code I am using to try and output the items but it makes the app crash
Does anyone know what the problem might be ?
Upvotes: 0
Views: 95
Reputation: 16338
Your app might be crashing because your pet basket contains nulls.
thisApp.petBasket.Add(lstAllPets.SelectedItem as Pets);
If the selected item is not a Pets
then operator as
returns null and you put that in the list. Later on you just iterate without checking for nulls.
foreach (Pets currpet in thisApp.petBasket)
{
lstBasketItems.Items.Add(currpet.Name + "" + currpet.Gender + "" + currpet.Dob + "" + currpet.Category + "");
}
You should check the selected item.
var pet = lstAllPets.SelectedItem as Pets;
if(pet != null)
thisApp.petBasket.Add(pet);
You could also check currpet
in your foreach
loop.
Upvotes: 1