RoadieRich RoadieRich - 28 days ago 13
C# Question

ComboBox.SelectedValue throws null reference exception

I've put together the following code to demonstrate a problem I'm having.

It's a form with just a combobox, which is populated using an array generated from LINQ in the load method.

It's got DisplayMember and ValueMember set. Display member works as expected - it displays a list of numbers. However, as commented, SelectedValue is null.

private void Form1_Load(object sender, EventArgs e)
{
comboBox1.DisplayMember = "Number";
comboBox1.ValueMember = "Square";

var it = from n in new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
select new NumberAndSquare(n);
comboBox1.Items.AddRange(it.ToArray());
}

private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
ComboBox combo = sender as ComboBox;
MessageBox.Show(combo.SelectedItem.ToString()); //works as expected
MessageBox.Show(combo.SelectedValue.ToString()); //throws null reference exception
}

class NumberAndSquare
{
public NumberAndSquare(int number)
{
Number = number;
}

public int Number
{ get; set; }
public int Square
{
get
{
return Number*Number;
}
}

public override String ToString()
{
return string.Format("{0}: {1}", Number, Square);
}
}


What am I doing wrong?

Answer

SelectedValue is no doubt null in this scenario because there is nothing being bound to it. AFAIK the DataMember/ValueMember properties are used only when you bind a DataSource to your combobox (which you aren't). For example, if you changed your code to:

var it = from n in new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
         select new NumberAndSquare(n);
comboBox1.DataSource = it.ToList();
comboBox1.DisplayMember = "Number";
comboBox1.ValueMember = "Square";

It should work

Comments