C# Update combobox bound to generic list

随声附和 提交于 2019-11-30 02:11:00

问题


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:


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.



来源:https://stackoverflow.com/questions/433281/c-sharp-update-combobox-bound-to-generic-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!