NullReferenceException was unhandled

2019-08-29 06:08发布

问题:

The application runs fine - But if the user selects NOTHING from the listboxes and instead just hits the 'Do We Match' button - that crashes the program. I need it to throw up an error requesting that they click a starsign in each list (official error is 'Null Reference Exception is unhandled).

Code for that part so far:

// 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!";

回答1:

Check the SelectedItem properties of your ListBoxes before you access the Content property of each ListBoxItem. Since you want both ListBoxes to have a value before you continue, put this check for null at the top of your Combinations method:

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

If there is no value selected in the ListBox, then the SelectedItem property will be null. So, when you get the ListBoxItem above:

ListBoxItem lbi = (ListBoxItem)yourListBox.SelectedItem;

lbi ends up with the value null. The NullReferenceException is thrown when you then try to get lbi.Content. Since lbi is null, it doesn't have an object to get the Content property from.



回答2:

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!";