Combobox selectedvalue

﹥>﹥吖頭↗ 提交于 2019-12-23 15:11:42

问题


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?


回答1:


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.




回答2:


try SelectedItem

MyObj obj = (MyObj)mycombobox.SelectedItem;



回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/4408492/combobox-selectedvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!