将对象添加到绑定列表<object>,重新排序并使组合框更新以反映更改



我有一个基本的Person类定义如下:

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

现在我要创建一个像这样的人的列表:

private List<Person> people = new List<Person>();
people.Add(new Person("John Smith", 21));
people.Add(new Person("Bob Jones", 30));
people.Add(new Person("Mike Williams", 35));

一旦我的列表被填充,我想按名字排序,像这样:

// make sure that the list of people is sorted before assigning to bindingList
people.Sort((person1, person2) => person1.Name.CompareTo(person2.Name));

接下来,我要创建一个BindingList,我将使用它作为一个组合框的数据源,如下所示:

private BindingList<Person> bindingList = new BindingList<Person>(people);
comboBoxPeople.DataSource = bindingList;
comboBoxPeople.DisplayMember = "Name";
comboBoxPeople.ValueMember = "Name";
到目前为止,这部分工作正常。但现在我有几个问题,我似乎无法得到解决。首先,我需要能够添加Person对象并保持列表的排序。现在,我可以添加一个新的Person对象到bindingList(通过bindingList.Add(newPerson)),它将显示在组合框中,尽管在底部(即,没有排序)。我怎么能重新排序绑定列表一旦我添加了一些东西,使它出现在组合框排序?

老实说,我认为你不需要特别的列表。用你手上的东西,不要白费力气。

这是一个类似的问题和解决方案:

BindingList.Sort()的行为类似于List.Sort()

最新更新