开发者

C# Dictionary as a ListBox.DataSource

开发者 https://www.devze.com 2022-12-25 07:21 出处:网络
I am trying to bind a dictionary as a DataSource to a ListBox.The开发者_StackOverflow solution in How to bind a dicationary to a ListBox in winforms will not work for me because my dictionary is a cla

I am trying to bind a dictionary as a DataSource to a ListBox. The开发者_StackOverflow solution in How to bind a dicationary to a ListBox in winforms will not work for me because my dictionary is a class-level variable and not a method-level variable, so I can not use var. When you put a class-level variable into new BindingSource(...) with null as the second argument I get an ArgumentNull exception.

How do I bind a class-level dictionary as a data source for a list box?

I don't like the List< KeyValuePair< string, string > > work-around becuase Where(...) and First(...) are ugly, complicated, and confusing compared to TryGetValue(...) and other Dictionary functionality.

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


I don't think the fact that it's a member variable will make a difference. To me, it looks like the important difference between Matt Hamilton's example and yours is that his dictionary has items in it, and yours doesn't. Your dictionary isn't null, but if the BindingSource constructor tries to get myDictionary.Values[0], that will be null.

Try putting an entry in the Dictionary, and see if you get different behaviour.


the same way, but at

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

put smthing like

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号