views:

350

answers:

2

I am trying to bind a dictionary as a DataSource to a ListBox. The 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
        }
    }
}          
A: 

the same way, but at

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

put smthing like

listBox1.DataSource = new BindingSource(YourClass.YourDict, null);
Andrey
+1  A: 

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.

Dan
Rats, forgive me for assuming that system libraries would check for the empty case...
Steve H.