2011-09-01 23 views
0

我有這樣的決定的基本Person類:添加對象的BindingList <object>,重新梳理,使組合框更新以反映變化

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.Add(newPerson)),它會顯示在組合框中,儘管在底部(即未排序)。我怎麼能重新排序bindingList,一旦我添加了一些東西,所以它顯示排序在comboBox?

+1

你嘗試回想起剛纔排序添加新元素後? – Tigran

+0

原來的.Sort()在它被分配給bindingList之前在變量列表上。當我需要添加一個新的Person對象時,它直接被添加到bindingList(顯然沒有.Sort()方法),所以在原List的變量上再次調用.Sort()將不會幫幫我。從我收集的信息來看,我需要實現某種可排序的bindingList才能工作,但我不確定。 – user685869

回答