C# 当没有选择时,为什么combobox SelectedValued抛出异常

C# 当没有选择时,为什么combobox SelectedValued抛出异常,c#,C#,我正在处理Windows窗体应用程序。。其中有许多文本框以及组合框这是我的数据输入表格。。。 当我将数据插入数据库时,出现了以下异常 string NickName = comboBox1.SelectedValue.ToString();//object reference not set to an instance of an object Nick Name在我的案例中是可选字段。。。 我的问题是为什么combobox SelectedValued在没有选择的情况下抛出异常?如何

我正在处理Windows窗体应用程序。。其中有许多文本框以及组合框这是我的数据输入表格。。。 当我将数据插入数据库时,出现了以下异常

   string NickName = comboBox1.SelectedValue.ToString();//object reference not set to an instance of an object
Nick Name在我的案例中是可选字段。。。 我的问题是为什么combobox SelectedValued在没有选择的情况下抛出异常?如何克服这个问题?。。 任何帮助都将不胜感激。提前谢谢

我的问题是为什么combobox SelectedValued在没有选择的情况下抛出异常

当选择nothig时
comboBox1.SelectedValue
返回
null
,如果在
null
上调用任何成员,它将抛出
NullReferenceException

如何克服这个问题

您可以在尝试访问其值之前检查
null


您可以检查其
SelectedIndex

解决方案:您可以使用以下任何一种方法来解决问题

方法1:使用
if条件

string NickName = string.Empty; 
if(comboBox1.SelectedValue != null)
   NickName = comboBox1.SelectedValue.ToString(); 
方法2:使用
条件(三元?:)运算符

string NickName = (comboBox1.SelectedValue != null) ? 
     comboBox1.SelectedValue.ToString() : string.Empty; 
方法3:使用
null合并???
运算符

string NickName =(string) comboBox1.SelectedValue ?? string.Empty; 
方法4:通过检查
SelectedIndex

string NickName = (comboBox1.SelectedIndex >= 0) ? 
     comboBox1.SelectedValue.ToString() : string.Empty; 

因为您正在尝试转换
null
对象

 string NickName = comboBox1.SelectedValue == null? "":comboBox1.SelectedValue.ToString();