【发布时间】:2013-05-09 16:27:13
【问题描述】:
为什么将ComboBox 的SelectedValue 设置为null 会导致ArgumentNullException?
仅当 ComboBox 实际上是表单的一部分时才会发生异常。
我可以将SelectedValue 设置为各种没有意义的值或类型,但我不能将其设置为null。
不是SelectedValue不能是null。事实上,在我尝试将其设置为 null 时,它的值 是 null。
在我的真实代码中,这不会发生在构造函数中,我也没有明确地将其设置为null。该代码使用了一个恰好是null 的变量。我可以通过在尝试设置SelectedValue 之前检查变量不是null 来修复它。但我不明白的是为什么我不能将它设置为null 值。
代码编辑:DataSource 现在包含一个项目,其中 ValueMembers 值实际上是 null
using System.Collections.Generic;
using System.Windows.Forms;
public class Form1 : Form {
public Form1() {
var comboBox1 = new ComboBox();
Controls.Add(comboBox1);
comboBox1.ValueMember = "Key";
comboBox1.DisplayMember = "Value";
comboBox1.DataSource = new List<Record> {
new Record {Key = "1", Value = "One"},
new Record {Key = null, Value = "null"}
};
comboBox1.SelectedItem = null; // no problem
comboBox1.SelectedValue = ""; // no problem
comboBox1.SelectedValue = new object(); // no problem
comboBox1.SelectedValue = null; // ArgumentNullException!!
}
}
public class Record {
public string Key { get; set; }
public string Value { get; set; }
}
【问题讨论】:
-
您是否有代码链接到 SelectedIndexChanged 事件或由当前值更改触发的其他事件?
-
看看这个问题是否有帮助。 stackoverflow.com/questions/2864065/…
-
@Steve:不。上面的示例代码是显示异常的完整工作示例。
标签: c# winforms combobox datasource nullreferenceexception