How to associate a ComboBox with a shared list with the deep DisplayMember and ValueMember properties?

I am trying to associate a general list, such as List List, with a ComboBox.

public Form1() { InitializeComponent(); List<Parent> parents = new List<Parent>(); Parent p = new Parent(); p.child = new Child(); p.child.DisplayMember="SHOW THIS"; p.child.ValueMember = 666; parents.Add(p); comboBox1.DisplayMember = "child.DisplayMember"; comboBox1.ValueMember = "child.ValueMember"; comboBox1.DataSource = parents; } } public class Parent { public Child child { get; set; } } public class Child { public string DisplayMember { get; set; } public int ValueMember { get; set; } } 

When I run my test application, I only see: "ComboBindingToListTest.Parent" appears in my ComboBox instead of "SHOW THIS". How can I bind a ComboBox to a General List through one level or deeper properties, for example. child.DisplayMember ??

Thanks Advance, Adolfo

+6
source share
3 answers

I do not think that you can do what you are trying. The design above shows that a parent can have only one child. It's true? Or you simplified the design for this question.

What I would recommend, regardless of whether the parent can have multiple children, is that you use an anonymous type as the data source for the combo box and populate that type with linq. Here is an example:

 private void Form1_Load(object sender, EventArgs e) { List<Parent> parents = new List<Parent>(); Parent p = new Parent(); p.child = new Child(); p.child.DisplayMember = "SHOW THIS"; p.child.ValueMember = 666; parents.Add(p); var children = (from parent in parents select new { DisplayMember = parent.child.DisplayMember, ValueMember = parent.child.ValueMember }).ToList(); comboBox1.DisplayMember = "DisplayMember"; comboBox1.ValueMember = "ValueMember"; comboBox1.DataSource = children; } 
+8
source

This will complete the task:

 Dictionary<String, String> children = new Dictionary<String, String>(); children["666"] = "Show THIS"; comboBox1.DataSource = children; comboBox1.DataBind(); 

If the "Children" were in the parent class, you can simply use:

 comboBox1.DataSource = parent.Children; ... 

However, if you need to bind multiple parents to the daughters, you can do the following:

 var allChildren = from parent in parentList from child in parent.Children select child comboBox1.DataSource = allChildren; 
0
source

You can simply intercept an event with a modified data source and perform specific object bindings there.

0
source

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


All Articles