C# Update combobox bound to generic list

前端 未结 1 859
遇见更好的自我
遇见更好的自我 2021-01-04 03:58

I have a combobox on my form that is bound to a generic list of string like this:

private List mAllianceList = new List();

priva         


        
相关标签:
1条回答
  • The easiest way around this would be to simply use a BindingList like so:

    private List<string> mAllianceList = new List<string>();
    private BindingList<string> bindingList;    
    
    private void FillAllianceList()
    {
        // Add alliance name to member alliance list
        foreach (Village alliance in alliances)
        {
            mAllianceList.Add(alliance.AllianceName);
        }
    
        bindingList = new BindingList<string>(mAllianceList);
    
        // Bind alliance combobox to alliance list
        this.cboAlliances.DataSource = bindingList;
    }
    

    Then, from here on out, just deal with the binding list to add and remove items from there. That will remove it both from the List and from the ComboBox.

    EDIT: To answer your question regarding sorting, I guess the easiest (but possibly "hacky" way to do it would be something like this:

    mAllianceList.Sort();
    bindingList = new BindingList<string>(mAllianceList);
    this.cboAlliances.DataSource = bindingList;
    

    So basically, after you sort, you create a new binding list and reset the data source. Maybe there's a more elegant way to go about this, however this should work.

    0 讨论(0)
提交回复
热议问题