简体   繁体   中英

Data binding on combo box

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>>

Binding a simple dictionary(key value pair) to combo box as display member and value member 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}"/>

You can do it in XAML, as follows:

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

Make sure you can bind to your collection (simple dictionary won't do, it's not an observable collection) - the example here uses data tables...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM