为什么设置SelectedValue
aComboBox
会null
导致 a ArgumentNullException
?
仅当 ComboBox 实际上是表单的一部分时才会发生异常。我可以设置SelectedValue
为各种没有意义的值或类型,但我不能将其设置为null
.
不是SelectedValue
不能null
。实际上,它的值是 null
在我尝试将其设置为null
.
在我的真实代码中,这不会发生在构造函数中,我也没有明确地将其设置为null
. 该代码使用的变量恰好是null
. 我可以通过null
在尝试设置SelectedValue
. 但我不明白为什么我不能将它设置为一个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; }
}