0

I've got a basic Person class defined like this:

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;
    }
}

Now I'm creating a list of people like this:

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));

Once my list has been populated, I want to sort it by name like this:

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

Next, I'm creating a BindingList which I will use as the datasource for a combobox like this:

private BindingList<Person> bindingList = new BindingList<Person>(people);

comboBoxPeople.DataSource = bindingList;
comboBoxPeople.DisplayMember = "Name";
comboBoxPeople.ValueMember = "Name";

So far, this much is working ok. But now I have a couple of problems that I can't seem to get fixed. First, I need to be able to add Person objects and have the list remain sorted. Right now, I can add a new Person object to the bindingList (via bindingList.Add(newPerson)) and it will show up in the comboBox, albeit at the bottom (i.e., not sorted). How can I re-sort the bindingList once I've added something to it so that it appears sorted in the comboBox?


I think honestly you don't need special list for this. Just use what you have in your hands, don't reinvent a wheel in other words.

Here is similiar question to yours and solution:

BindingList<T>.Sort() to behave like a List<T>.Sort()

4

1 回答 1

0

老实说,我认为您不需要为此特别列出。只使用你手中的东西,换句话说,不要重新发明轮子。

这是与您的问题和解决方案类似的问题:

BindingList<T>.Sort() 表现得像 List<T>.Sort()

于 2011-09-02T05:44:24.820 回答