Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data binding on combo box

Tags:

c#

I am adding items to a combo box as given below:

   readonly Dictionary<string, string> _persons = new Dictionary<string, string>();
   ....
   //<no123, Adam>, <no234, Jason> etc..
   foreach (string key in _persons.Keys)
   {
        //Adding person code
        cmbPaidBy.Items.Add(key);                   
   }

I want make the combo box more readable by displaying the values from dictionary (ie Names). But I need the person codes (no123 etc) for fetching from the database based on user input.

What is the right way to do this? How can I bind both value and key to combo box item?

like image 638
softwarematter Avatar asked Apr 08 '26 10:04

softwarematter


2 Answers

The DisplayMember and the ValueMember properties are there for you :

cmbPaidBy.DataSource = new BindingSource(_persons, null); 
cmbPaidBy.DisplayMember = "Value"; 
cmbPaidBy.ValueMember = "Key"; 

more in depth information here, and here on the BindingSource Class

The BindingSource component serves many purposes. First, it simplifies binding controls on a form to data by providing currency management, change notification, and other services between Windows Forms controls and data source

like image 70
Caspar Kleijne Avatar answered Apr 10 '26 23:04

Caspar Kleijne


Since Dictionary<TKey, TValue> does not implement IList (or any of the other data source interfaces), it cannot be used as a data source for binding. You could use an alternative representation, such as a DataTable or List<KeyValuePair<TKey, TValue>>.

In the latter case, you could bind easily using the following code:

cmbPaidBy.ValueMember = "Key";
cmbPaidBy.DisplayMember = "Value";
cmbPaidBy.DataSource = _persons; // where persons is List<KeyValuePair<string,string>>
like image 34
Bradley Smith Avatar answered Apr 10 '26 23:04

Bradley Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!