C#更新组合框绑定到泛型列表 [英] C# Update combobox bound to generic list

查看:332
本文介绍了C#更新组合框绑定到泛型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的窗体上的组合框绑定到字符串这样一个普通的列表:

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;
}



然后用户可以添加或删除在组合框中的项目。

我在其他地方,通过简单地添加或删除在通用列表中的项目,组合框的内容会自动更新读取;如果我使用排序()就可以了应该发生同样的事情。

但由于某些原因,我不能做这项工作。我可以看到组合框的DataSource属性正确更新为我添加/删除/项目进行排序,但在下拉列表中显示的内容是不是那些在DataSource属性。

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!

编辑:

的答案我选择了解决这个问题的添加和删除,而是一个的BindingList对象不能排序,这是必要的我。我发现,其中一个自定义类是通过继承的BindingList和添加排序功能建立了一个解决方案,但我想知道是否有在我的情况下,更容易的解决方案。

关于如何解决这个任何建议?容易

推荐答案

解决这个问题的最简单的方法是简单地使用的BindingList像这样:

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;
}



然后,从这里开始了,只是处理绑定列表添加和从那里删除项目。 。这将既从列表从ComboBox删除

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.

编辑:回答你关于排序的问题,我想最简单的(但可能哈克的方式做这将是这样的:

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.

这篇关于C#更新组合框绑定到泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆