Why does setting the SelectedValue
of a ComboBox
to null
cause an ArgumentNullException
?
The Exception only occurs if the ComboBox is actually part of a Form.
I can set SelectedValue
to all kinds of values or types that don't make sense, but I can't set it to null
.
It's not that SelectedValue
can not be null
. In fact, its value is null
at the time I'm trying to set it to null
.
In my real code, this doesn't happen in the constructor, and I'm not excplicitly setting it to null
. The code is using a variable which happens to be null
. I can fix it by checking of the variable isn't null
before trying to set the SelectedValue
. But what I don't understand is why I can't set it to a null
value.
Code edit: DataSource now contains an item where the ValueMembers value is actually 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; }
}