为什么我的Windows手机应用程序会因按钮点击而崩溃?

时间:2014-03-21 14:58:26

标签: c#

我正在为visual studio 2010中的windows phone 7制作一个宠物店应用程序。我试图从一个页面中获取已经复制到app.xaml临时列表中的项目(可以在调试器中看到)要在篮子页面上的其他列表中显示,但是当单击指向篮子页面的按钮时,应用程序崩溃。我没有对应用程序的任何部分使用绑定

 private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        thisApp.petBasket.Add(lstAllPets.SelectedItem as Pets);
        MessageBox.Show("Item added to the Basket");
    }

这是用于将项目添加到临时列表的代码

    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 + "");
            }
        }
    }

这是我用来尝试输出项目但却导致应用程序崩溃的代码

有谁知道问题可能是什么?

1 个答案:

答案 0 :(得分:1)

您的应用可能会崩溃,因为您的宠物篮子中包含空值。

thisApp.petBasket.Add(lstAllPets.SelectedItem as Pets);

如果所选项目不是Pets,那么operator as将返回null并将其放入列表中。稍后您只需迭代而不检查空值。

foreach (Pets currpet in thisApp.petBasket)
{
    lstBasketItems.Items.Add(currpet.Name + "" + currpet.Gender + "" + currpet.Dob + "" + currpet.Category + "");
}

您应该检查所选项目。

var pet = lstAllPets.SelectedItem as Pets;
if(pet != null)
    thisApp.petBasket.Add(pet);

您还可以在currpet循环中查看foreach

相关问题