NullReferenceException未处理

时间:2011-12-15 22:14:40

标签: c# listbox windows-phone nullreferenceexception

应用程序运行正常 - 但是如果用户从列表框中选择NOTHING而只是点击“Do We Match”按钮 - 那会导致程序崩溃。我需要它来发出一个错误,要求他们点击每个列表中的一个星号(官方错误是'空引用异常未处理)。

到目前为止该部分的代码:

// Method for starsign combinations
public void Combinations()
{
    ListBoxItem lbi = (ListBoxItem)yourListBox.SelectedItem;
    string yourListBoxValue = (string)lbi.Content;

    ListBoxItem lbi2 = (ListBoxItem)partnerListBox.SelectedItem;
    string partnerListBoxValue = (string)lbi2.Content;

    string listBoxValuesCombined = yourListBoxValue + partnerListBoxValue;

    if ((listBoxValuesCombined == "Aries" + "Aries") || (listBoxValuesCombined == "Aries" + "Aries"))
        resultTextBlock.Text = "On Fire - this is a hot combination!";

2 个答案:

答案 0 :(得分:0)

public void Combinations()
{
    if ((ListBoxItem)yourListBox.SelectedItem == null 
      || (ListBoxItem)partnerListBox.SelectedItem == null) return;

    ListBoxItem lbi = (ListBoxItem)yourListBox.SelectedItem;
    string yourListBoxValue = (string)lbi.Content;

    ListBoxItem lbi2 = (ListBoxItem)partnerListBox.SelectedItem;
    string partnerListBoxValue = (string)lbi2.Content;



    string listBoxValuesCombined = yourListBoxValue + partnerListBoxValue;

    if ((listBoxValuesCombined == "Aries" + "Aries") || (listBoxValuesCombined == "Aries" + "Aries"))
        resultTextBlock.Text = "On Fire - this is a hot combination!";

答案 1 :(得分:0)

在访问每个ListBoxItem的Content属性之前,请检查ListBoxes的SelectedItem属性。由于您希望在继续之前两个ListBox都具有值,因此请在组合方法的顶部将此检查为null:

public void Combinations()
{
  if (yourListBox.SelectedItem == null || partnerListBox.SelectedItem == null)
  {
    resultTextBlock.Text = "Please select a sign for yourself and your partner.";
    return;
  }

如果ListBox中没有选择值,则SelectedItem属性将为null。所以,当你得到上面的ListBoxItem:

ListBoxItem lbi = (ListBoxItem)yourListBox.SelectedItem;

lbi最终得到null值。当你尝试获取lbi.Content时抛出NullReferenceException。由于lbi为null,因此它没有从中获取Content属性的对象。