C# Update combobox bound to generic list

2020-03-01 07:21发布

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

private List<string> mAllianceList = new List<string>();

private void FillAllianceList()
{
    // Add alliance name to member alliance list
    foreach (Village alliance in alliances)
    {
        mAllianceList.Add(alliance.AllianceName);
    }

    // Bind alliance combobox to alliance list
    this.cboAlliances.DataSource = mAllianceList;
}

The user may then add or remove items in the combobox.
I have read elsewhere that by simply adding or removing the item in the generic list, the contents of the combobox should automatically be updated; same thing should occur if I use Sort() on it.
But for some reason, I cannot make this work. I can see the combobox's DataSource property is correctly updated as I add/remove/sort items, but the contents displayed in the combobox are not those in the DataSource property.

I am surely missing something or doing something wrong.
Thanks in advance!

EDIT:
The answer I chose solved the issue for adding and removing, but a BindingList object cannot be sorted, and this is necessary for me. I've found a solution where a custom class is built by inheriting BindingList and adding sorting capabilities, but I would like to know if there's an easier solution in my case.
Any suggestions on how to solve this easily?

1条回答
疯言疯语
2楼-- · 2020-03-01 07:53

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.

查看更多
登录 后发表回答