Tuesday 29 January 2008

ComboBox Databinding to List<int>

A bit of a weird one to start off the blog but here goes anyway...

I was trying to bind a List<int> to the datasource of a combo box in Windows forms C# and got the following error message "Cannot set the SelectedValue in a ListControl with an empty ValueMember."

Okay, admittedly I hadn't set the ValueMember or the DisplayMember of the combobox but what should i set them to? From what I thought was a simple thing to do suddenly caused me a little trouble..mmmm.

Anyway, a bit more investigation and I found that I was setting the "SelectedValue" property of the combobox but what I needed to be doing was setting the "SelectedItem" property of the combobox.

Wrong way:

public int ParentPosDepartmentId
{
set { this.ParentIdComboBox.SelectedValue = value; }
}


Right way:



public int ParentPosDepartmentId
{
set { this.ParentIdComboBox.SelectedItem = value; }
}


Well there is a nice simple problem to start this blog off with, I hope the issues I tackle will get a little bit more involved than this, but hey its a start :-)



Cheers

2 comments:

Anonymous said...

Awesome! thanks, you just saved me no end of pain!

Anonymous said...

Just came here by Google because I had exactly the same problem. Simple solution which worked perfectly for me! Thank you very much!