【问题标题】:C# Dictionary as a ListBox.DataSourceC# 字典作为 ListBox.DataSource
【发布时间】:2011-02-02 14:39:46
【问题描述】:

我正在尝试将字典作为 DataSource 绑定到 ListBox。 How to bind a dicationary to a ListBox in winforms 中的解决方案对我不起作用,因为我的字典是类级变量而不是方法级变量,所以我不能使用 var。当您将一个类级变量放入 new BindingSource(...) 时,将 null 作为第二个参数,我得到一个 ArgumentNull 异常。

如何将类级字典绑定为列表框的数据源?

我不喜欢 List> 解决方法,因为与 TryGetValue(...) 相比, Where(...) 和 First(...) 丑陋、复杂且令人困惑和其他字典功能。

namespace myNamespace
{
    public partial class myForm : Form
    {
        private Dictionary<string,string> myDictionay;
        public myForm()
        {
            InitializeComponent();
            myDictionay= new Dictionary<string, string>();
            listBox1.DataSource = new BindingSource(myDictionay,null);  // ArguemtNull exception
        }
    }
}          

【问题讨论】:

  • 你确定你对象上的字典不为空吗?我们可能需要更多代码
  • 我在 DataSource 分配上方的一行实例化字典 - 字典不为空。

标签: c# dictionary listbox datasource


【解决方案1】:

以同样的方式,但在

listBox1.DataSource = new BindingSource(choices, null);

放东西

listBox1.DataSource = new BindingSource(YourClass.YourDict, null);

【讨论】:

    【解决方案2】:

    我不认为它是一个成员变量这一事实会有所作为。对我来说,看起来马特汉密尔顿的例子和你的例子之间的重要区别在于他的字典中有项目,而你的没有。您的字典不为空,但如果 BindingSource 构造函数尝试获取 myDictionary.Values[0],则 为空。

    尝试在字典中输入一个条目,看看你是否会得到不同的行为。

    【讨论】:

    • 老鼠,请原谅我假设系统库会检查空箱...
    猜你喜欢
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多