Data binding on combo box
I am adding items to a combo box as given below:
readonly Dictionary<string, string> _persons = n开发者_运维知识库ew 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>>
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...
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}"/>
精彩评论