How to bind to the list and swap at the same time?

I have data about the form that I want to associate with lists. Combined fields must constantly display the same object and bind to different properties of the object, but one of them displays only a subset of all possible objects.

My objects can be described as:

{"q",#1,1},{"w",#1,2},{"e",#1,3},{"r",#2,6},{"t",#3,2},{"y",#3,6} etc 

The first combo box displays the first box and the full list, to be precise:

 "q","w","e","r","t","y" etc 

The second combo box displays the third field, but only for objects that have a similar second field with the currently selected object.

If {"q", # 1,1} is selected, it displays:

 1,2,3 

and if {"r", # 2,6} is selected, it will display:

 6 

Selecting another item in any of the combo boxes changes the currently selected item and (which accordingly updates the other relevant fields).

What is the most elegant or β€œright” way to do this using winforms data binding? (for me, elegat will not resort to handling changes to the currently selected item).

+4
source share
2 answers

This can help:

 List<Tuple<string, string, int>> values = new List<Tuple<string, string, int>>(); 

Then:

 comboBox1.DisplayMember = "Item1"; comboBox1.DataSource = values; comboBox2.DisplayMember = "Item3"; var filter = ((Tuple<string, string, int>)comboBox1.SelectedItem).Item2; comboBox2.DataSource = values.Where(input => input.Item2 == filter); 
+1
source

Create a property for each of your ComboBoxes to bind. Now, in fact, properties can be a LINQ expression, filtering the right data for you.

An example of such properties:

 private final List<MyObj> _allObjects = new List<MyObj>(); ... // fill the _allObjects somewhere public IEnumerable<MyObj> AllGoodObjects { get { return from o in _allObjects where o.IsGood select o; } } public IEnumerable<MyObj> AllBadObjects { get { return from o in _allObjects where !o.IsGood select o; } } 

You can create a complex query and practically select whatever you want.

0
source

All Articles