ComboBox.SelectedValue.ToString() 抛出 NullReferenceException

ComboBox.SelectedValue.ToString() throw NullReferenceException

在我的 VS 2022 社区版 WindowsForms 项目中:我有一个带有 SelectedValueChange 事件的组合框,但仍然出现错误:

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

代码:

private void cmbChooseTask_SelectedValueChanged(object sender, EventArgs e)
{
    if (cmbChooseTask.SelectedValue.ToString() == "Install non clusterd instance")
    {
        Form frm = new NonClusterdInstallation();
        frm.Show();
    }

}

组合框初始化为:

            cmbChooseTask.DataSource = new BindingSource(Dictionaries.DictTypeOfTask, null);
        cmbChooseTask.DisplayMember = "Value";
        cmbChooseTask.ValueMember = "Value";
        cmbChooseTask.SelectedItem = null;

字典定义是:

        public static SortedDictionary<int, string> DictTypeOfTask = new SortedDictionary<int, string>()
    {
        { 1,"Install non clusterd instance" },
        { 2,"Install clusterd instance"},
        { 3, "Set up pre-installed cluster instance" },
        { 4, "Migration" },
        { 5, "Change Collation" },
        { 6, "Add instance to cluster" },
        { 7, "Display all" }
    };

NRE 的快速解决方案是:

if (String.Equals(cmbChooseTask.SelectedValue?.ToString(), "Install non 
clusterd instance"))

或者只是

if (cmbChooseTask.SelectedValue?.ToString() == "Install non 
clusterd instance")

既然已经是 string,为什么还要调用 ToString?只需将其转换为 string 类型,null 也会成功:

if ((string)cmbChooseTask.SelectedValue == "Install non clusterd instance")

此外,根据您与之比较的文本,我猜您实际上关心控件中显示的文本,该文本通过 Text 属性、这已经是类型 string:

if (cmbChooseTask.Text == "Install non clusterd instance")