4

I have a combobox on my form (winforms). In the properties I have set the DisplayMember and the ValueMember. DisplayMember = Name and ValueMember = ID. The Combobox is populated with the following objects:

public class MyObj { public string Name { get; set; } public int ID { get; set; } } 

The Name displays fine in the dropdown(so DisplayMember is working) however, when I do:

mycombobox.SelectedValue it is ALWAYS null.

Does anyone know if I've forgotten to do anything?

6
  • where did you check mycombobox.SelectedValue ? Commented Dec 10, 2010 at 11:47
  • It's on the click event of a button. I have also tried checking it on the SelectedIndexChanged event of the combobox itself but it didn't work there either. Commented Dec 10, 2010 at 11:50
  • if you do SelectedIndex or SelectedItem what do you get? can you add the code of how the combobox is configured and populated? Commented Dec 10, 2010 at 11:50
  • Try to swap ID and Name: DisplayMember = ID and ValueMember = Name and see if ID displays fine in the dropdown to make sure your datasource is fine. Commented Dec 10, 2010 at 11:53
  • I set DisplayMember = ID and it displays the ID just fine. Commented Dec 10, 2010 at 11:54

4 Answers 4

4

Have you set the DataSource property. Also make sure that you have to set them in the correct order -

Set them in the following order -

1. DisplayMember 2. ValueMember 3. DataSource 

See this link - http://social.msdn.microsoft.com/Forums/en/winformsdatacontrols/thread/211a46f5-5971-4ea2-a61d-84e389360909

Alternatively you can use the SelectedItem property to get the selected MyObj instance.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I ended up just using the SelectedItem property and casting.
THANK YOU for the order comment! Saved me so much time!
0

try SelectedItem

MyObj obj = (MyObj)mycombobox.SelectedItem; 

Comments

0

Has an item been selected? Selected is not always the same as visible. Perhaps you really want to mycombobox.Text.

Comments

0

I have similar mistake. I set DisplayMember and ValueMember, but i set instead of DataSource Items.Insert.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.