ComboBox.SelectedValue.ToString() throw NullReferenceExcepti



在我的VS 2022社区版,WindowsForms项目:我有一个组合框与SelectedValueChange事件,仍然得到一个错误:

系统。NullReferenceException: 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")

最新更新