Combining data in a combo box

I am adding items to the combo box as shown 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 to make the combo box more readable by showing the values ​​from the dictionary (i.e. names). But I need human codes (no123, etc.) to retrieve from the database based on user input.

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

+3
source share
4 answers

DisplayMember and ValueMember properties are available to you:

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

more information here and here in the BindingSource Class

BindingSource . -, , Windows Forms

+5

Dictionary<TKey, TValue> IList ( ), . , DataTable List<KeyValuePair<TKey, TValue>>.

:

cmbPaidBy.ValueMember = "Key";
cmbPaidBy.DisplayMember = "Value";
cmbPaidBy.DataSource = _persons; // where persons is List<KeyValuePair<string,string>>
+1

XAML, :

<ComboBox ItemsSource="{Binding Persons}" DisplayMemberPath="Key" ValueMemberPath="Value" />

, ( , ) - ...

0

Associating a simple dictionary (key value pair) with a combo box as a display element and value element in XAML

<ComboBox Height="23" HorizontalAlignment="Left" SelectedItem="{Binding SelectedKeyValue}" SelectedValuePath="Value"  DisplayMemberPath="Key" Width="120"     x:Name="comboBox1" />

   <TextBox Height="23" HorizontalAlignment="Left" Name="textBox1" Width="120" Text="{Binding Path=SelectedValue, ElementName=comboBox1, Mode=TwoWay}"/>
0
source

Source: https://habr.com/ru/post/1768182/


All Articles