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

查看:24
本文介绍了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;
}

然后用户可以在组合框中添加或删除项目.
我在别处读到通过简单地添加或删除通用列表中的项目,组合框的内容应该自动更新;如果我在它上面使用 Sort() 也会发生同样的事情.
但由于某种原因,我无法完成这项工作.我可以看到组合框的 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;
}

然后,从现在开始,只需处理绑定列表以从那里添加和删除项目.这将从列表和组合框中删除它.

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.

为了回答你关于排序的问题,我想最简单的(但可能是hacky"的方法是这样的:

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天全站免登陆