【问题标题】:Null error when trying to access values in a combobox wpf [duplicate]尝试访问组合框 wpf 中的值时出现空错误 [重复]
【发布时间】:2021-04-24 21:32:35
【问题描述】:

我正在尝试根据组合框中选择的内容进行一些计算,但我不断收到 System.NullReferenceException: 'Object reference not set to an instance of an object。作为一个错误。

这是我的代码,错误出现在if语句的那一行:

private void TokenWorthtxtBox_TextChanged(object sender, TextChangedEventArgs e)
{
    if (BookCondition.SelectedItem == null || BookGenre.SelectedItem == null || BookFormat.SelectedItem == null || BookExamBoard.SelectedItem == null)//this is where the error appears
    {
        errormessage.Text = "Please select values from the drop down boxes.";
    }
    else
    {
        int tokenPrice = BookPriceCalculation(BookTitleTxtBox.Text, BookCondition.SelectedItem.ToString(), BookGenre.SelectedItem.ToString(), BookFormat.SelectedItem.ToString(), BookExamBoard.SelectedItem.ToString());
        DisplaySuggestedTokentxtBlock.Text = $"Suggested Token: {tokenPrice}";
    }
}

【问题讨论】:

标签: c# wpf combobox


【解决方案1】:

它在第一个'if'中控制的对象可以为null,因此它们以'?'结尾如果你添加它,你的问题就可以解决。

    if (BookCondition?.SelectedItem == null || BookGenre?.SelectedItem == null || BookFormat?.SelectedItem == null || BookExamBoard?.SelectedItem == null)
    {
        errormessage.Text = "Please select values from the drop down boxes.";
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2016-04-19
    • 2018-07-17
    相关资源
    最近更新 更多