Items on ListBox show up as a class name

懵懂的女人 提交于 2019-12-01 06:12:56

In the Person class override the ToString method:

public class Person
{
    private int id;
    private string name;

    public Person(int m_id, string m_name)
    {
        id = m_id;
        name = m_name;
    }

    public int Id
    {
        get
        {
            return id;
        }
    }

    public string Name
    {
        get
        {
            return name;
        }
    }
    public override string ToString()
    {
        return name;
    }
}

With this whenever you set the listbox datasource to a List<Person> the listbox will automatically use the ToString method as the display. Using the selecteditem is simply a matter of casting it as Person, (Person)listBox1.SelectedItem.

Did some more investigating and found out when you set the datasource to null it cleared the DisplayMemeber value. Set it after you set a new Datasource and the problem disappears.

listBox1.DataSource = null;    // this is optional. Commenting this line out doesn't help
persons.Add(new Person(1, "John Doe"));
persons.Add(new Person(2, "Jane Doe"));
persons.Add(new Person(3, "Somebody Else"));
listBox1.DataSource = persons;
listBox1.DisplayMember = "Name";

Try setting the "ValueMember" and "DisplayMember" properties only once before any datasource binding. Can you set them in the designer? Then always before changing the datasource, run ListBox's "ClearSelected()"-method to clear any selections. Then unbind the datasource, edit the list, then set the edited list as datasource. Seems that this behavior is some kind of bug. Try if this helps.

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