Home » c# » c# – DataSource DisplayMember with custom string composed of DataSource properties-Exceptionshub

c# – DataSource DisplayMember with custom string composed of DataSource properties-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

Is it possible to bind a ListBox to a DataSource of List<A>, while setting the DisplayMember to a custom string composed of A’s properties, such as the following $"{A.b} {A.c}"?

var list1 = new List<A>();
// populate list
MyListBox.DisplayMember = $"{A.b} {A.c}"; // not going to work
MyListBox.DataSource = list1;

I know I can use an anonymous type, but I want the ListBox.Items to remain of type A. I don’t want to do the following,

var list2 = (from a in list1
             select new {A = a, DisplayMember = $"{a.b} {a.c}"}).ToList();
MyListBox.DisplayMember = "DisplayMember";
MyListBox.DataSource = list2;

because now MyListBox.Items is anonymous and A can’t be retrieved like var list = MyListBox.Items.OfType<A>().

So, is there any way to do that?

How to&Answers:

I was thinking about it wrong. Solved it now. Maybe it was obvious to some, but I’m going to post my answer for posterity.

Use the anonymous type in the second example, and just set the ValueMember to A

var list2 = (from a in list1
             select new {A = a, DisplayMember = $"{a.b} {a.c}"}).ToList();
MyListBox.DisplayMember = "DisplayMember";
MyListBox.ValueMember = "A";
MyListBox.DataSource = list2;

var list3 = MyListBox.Items.OfType<A>().ToList(); // works!