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?
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
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>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With