清除方法以捕获错误未设置对象引用

时间:2015-05-08 12:41:40

标签: c# object-reference

当DeliveryMethodComboBox没有selectedItem时,

  

对象引用未设置为对象的实例。

出现

错误。

解决这个问题的最佳方法是什么? 在这个例子中,我添加了一个try和catch。

try
{
    DeliveryMethodLabel2.Text = DeliveryMethodComboBox.SelectedItem.ToString();
}
catch 
{
    DeliveryMethodLabel2.Text = "";
}

1 个答案:

答案 0 :(得分:1)

我假设你的意思是值为空

**假设您的列表中没有空值,并且您只关心是否有选择。

if(DeliveryMethodComboBox.SelectedIndex != -1)
{
    DeliveryMethodLabel2.Text = DeliveryMethodComboBox.SelectedItem.ToString();
}
else
{
    DeliveryMethodLabel2.Text = "";
}

否则,如果DeliverMethodComboBox可以为null,只需将if更改为

即可
if(DeliveryMethodComboBox != null && DeliveryMethodComboBox.SelectedIndex != -1)