【问题标题】:How to set SelectedValue of a List bound Combobox with an item not available in the List如何使用列表中不可用的项目设置列表绑定组合框的 SelectedValue
【发布时间】:2010-09-03 06:06:12
【问题描述】:

我有一个包含 Person 类对象的列表。我已将列表设置为 ComboBox 的数据源。现在,当我将 ComboBox 的 SelectedItem 设置为 Person 类的新实例时,SelectedItem 永远不会设置。为什么会这样?

    public class Person
    {
        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public List<Person> lstPerson = new List<Person>();

    private void Form1_Load(object sender, EventArgs e)
    {
        lstPerson.Add(new Person("Name1",1));
        lstPerson.Add(new Person("Name2",2));

        comboBox1.DataSource = lstPerson;
        comboBox1.DisplayMember = "Name";

        comboBox1.SelectedItem = lstPerson[1]; //If I put this line then it works
        //comboBox1.SelectedItem = new Person("Name2", 2); // Not working if I put this line. How can I make this possible?
    }

我应该怎么做才能让这段代码正常工作?我在很多论坛上都问过这个问题。从来没有得到任何解决方案。

【问题讨论】:

    标签: c# data-binding combobox datasource selecteditem


    【解决方案1】:

    ComboBox 类使用 IndexOf 方法搜索指定的对象。此方法使用 Equals 方法来确定相等性。

    你可以在你的 Person 对象上覆盖 Equals(object obj) 来实现你的目标

    【讨论】:

    • ComboBox 将尝试将指定的值与其数据源中实际存在的值相匹配。覆盖 Equals 不会让您有任何收获。
    • 是的,你是对的,但请注意 Rajeesh 只想选择他的问题中的第二项,("Name2", 2) 已经存在于他的数据源中
    • 好的。非常感谢你的答复。让我研究一下。
    猜你喜欢
    • 2013-08-09
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多