为什么将SelectedValue的ComboBox设置为null会导致ArgumentNullException
只有当ComboBox实际上是表单的一部分时,才会发生异常。我可以将SelectedValue设置为各种没有意义的值或类型,但不能将其设置为null。
并不是SelectedValue不能成为null。实际上,在我试图将其设置为null时,它的值是null。
在我的实际代码中,这不会发生在构造函数中,而且我也不会将其设置为null。代码使用的变量恰好是null。在尝试设置null之前,我可以通过检查变量不是SelectedValue来修复它。但我不明白的是,为什么我不能将它设置为null值。
代码编辑:DataSource现在包含一个ValueMembers值实际上是null的项
代码语言:javascript运行复制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
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; }
}