开发者

Add object to BindingList<object>, re-sort and make comboBox update to reflect change

开发者 https://www.devze.com 2023-04-01 03:56 出处:网络
I\'ve got a basic Person class d开发者_Python百科efined like this: public class Person { public string Name { get; set; }

I've got a basic Person class d开发者_Python百科efined 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()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号