未处理NullReferenceException [英] NullReferenceException was unhandled

查看:117
本文介绍了未处理NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该应用程序运行良好-但是,如果用户从列表框中选择无",而只是点击执行匹配"按钮-则该程序将崩溃.我需要它引发一个错误,要求他们在每个列表中单击星号(官方错误是未处理空引用异常".)

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

推荐答案

在访问每个ListBoxItem的Content属性之前,请检查ListBoxes的SelectedItem属性.由于您希望两个ListBox都具有一个值,然后再继续,因此请将此检查是否为null放在Combinations方法的顶部:

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;
  }

如果在列表框中没有选择任何值,则SelectedItem属性将为null.因此,当您获得上面的ListBoxItem时:

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的最终值为null.然后,当您尝试获取lbi.Content时,将引发NullReferenceException.由于lbi为null,因此它没有对象来获取Content属性.

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.

这篇关于未处理NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆