Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding Combobox Using Dictionary as the Datasource

I'm using .NET 2.0 and I'm trying to bind a combobox's Datasource to a sorted dictionary.

So the error I'm getting is "DataMember property 'Key' cannot be found on the Datasource".

        SortedDictionary<string, int> userCache = UserCache.getSortedUserValueCache();         userListComboBox.DataSource = new BindingSource(userCache, "Key"); //This line is causing the error         userListComboBox.DisplayMember = "Key";         userListComboBox.ValueMember = "Value"; 
like image 992
user803952 Avatar asked Jun 20 '11 14:06

user803952


People also ask

How to bind ComboBox with dictionary in c#?

Show activity on this post. SortedDictionary<string, int> userCache = new SortedDictionary<string, int> { {"a", 1}, {"b", 2}, {"c", 3} }; comboBox1. DataSource = new BindingSource(userCache, null); comboBox1. DisplayMember = "Key"; comboBox1.

How do I bind a ComboBox?

To bind a ComboBox or ListBox control If you are binding to a table, set the DisplayMember property to the name of a column in the data source. If you are binding to an IList, set the display member to a public property of the type in the list.

What is ComboBox control in C#?

ComboBox Control C# controls are located in the Toolbox of the development environment. You can use them to create objects on a form with a simple series of mouse clicks and dragging motions. A ComboBox displays a Textbox combined with Listbox, which enables the user to select items from the list or enter a new value.


1 Answers

SortedDictionary<string, int> userCache = new SortedDictionary<string, int> {   {"a", 1},   {"b", 2},   {"c", 3} }; comboBox1.DataSource = new BindingSource(userCache, null); comboBox1.DisplayMember = "Key"; comboBox1.ValueMember = "Value"; 

But why are you setting the ValueMember to "Value", shouldn't it be bound to "Key" (and DisplayMember to "Value" as well)?

like image 173
Sorin Comanescu Avatar answered Sep 22 '22 23:09

Sorin Comanescu