[英]C# Error when setting ListBox.DataSource = null (Possible event firing issue?)
[英]C# Dictionary as a ListBox.DataSource
我正在尝试将字典作为数据源绑定到ListBox。 对于我来说, 如何将字典与WinForms中的ListBox绑定在一起的解决方案对我不起作用,因为我的字典是类级别的变量,而不是方法级别的变量,因此我不能使用var。 当您将类级别的变量放入新的BindingSource(...)中,并将null作为第二个参数时,我得到ArgumentNull异常。
如何将类级词典绑定为列表框的数据源?
我不喜欢List <KeyValuePair <string,string>>解决方法,因为与TryGetValue(...)和其他Dictionary相比,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
}
}
}
我认为这不是成员变量这一事实不会有所作为。 在我看来,马特·汉密尔顿(Matt Hamilton)的例子与您的例子之间的重要区别在于,他的词典中有项目,而您的字典中没有。 您的字典不为null,但是如果BindingSource构造函数尝试获取myDictionary.Values [0],则它将为null。
尝试在“字典”中放置一个条目,看看是否有其他行为。
同样的方法,但是
listBox1.DataSource = new BindingSource(choices, null);
像
listBox1.DataSource = new BindingSource(YourClass.YourDict, null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.