处理 Class.SelectedItem.Value 的空值

Handling null value of Class.SelectedItem.Value

我有以下代码,它是按钮的点击事件:

protected void btnSave_Click(object sender, EventArgs e)
{
    Button btn = sender as Button;
    CheckBoxList cbl = btn.Parent.FindControl("chkbx_list") as CheckBoxList;
            
    if (cbl.SelectedItem.Value != null) //***Exception is thrown here***
    {
    //Do Stuff
    }
}

如何检查 cbl.SelectedItem.Value 中的值是否为空?当我尝试“引用”该值时,应用程序抛出以下错误:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Web.UI.WebControls.ListControl.SelectedItem.get returned null.

问题是您在检查 null 对象是否为 null 之前尝试对 null 对象使用 toString() 方法。 您需要先检查父对象值。

因为我无法发表评论,所以我应该在您更改 problem.when 用作铸造对象的关键字时更改我的答案,如果铸造失败,它可能 return null,请检查 cbl value 先看是否为null.

根据异常消息,问题是 SelectedItemnull 并且您正在尝试从该空实例访问成员。

首先检查要访问的成员不为空,避免空引用异常。

这是详细的方法

if (cbl.SelectedItem != null && cbl.SelectedItem.Value != null)

或使用null-conditional operator

if (cbl?.SelectedItem?.Value != null)