Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind a collection of C# 7.0 tuple type values to a System.Windows.Forms.Listbox and set the display member to one of the elements?

I have a System.Windows.Forms.Listbox and a collection of tuple type values I've created. That is, the new tuple type introduced in C# 7.0. I'm trying to bind the collection to the Listbox and set the DisplayMember to one of the elements in the tuple. Here's an example:

var l = new List<(string name, int ID)>()
{
    ("Bob", 1),
    ("Mary", 2),
    ("Beth", 3)
};

listBox1.DataSource = l;
listBox1.DisplayMember = "name";

That doesn't work, though. With the older-style Tuple<T> you could supposedly do what's described in this answer:

listBox1.DisplayMember = "Item1";
listBox1.ValueMember = "Item3";   // optional

That doesn't work either. Here's what I'm seeing in both cases:

enter image description here

How can I accomplish this?

like image 672
rory.ap Avatar asked Dec 12 '17 15:12

rory.ap


2 Answers

Unfortunately C#7 value tuples cannot be used for data binding because they use fields, while Windows Forms standard data binding works only with properties.

like image 167
Ivan Stoev Avatar answered Oct 20 '22 19:10

Ivan Stoev


Ivan's answer, definitely describes the case. As a workaround you can use Format event of ListBox to show name filed:

private void listBox1_Format(object sender, ListControlConvertEventArgs e)
{
    e.Value = (((string name, int ID))e.ListItem).name;
}
like image 43
Reza Aghaei Avatar answered Oct 20 '22 21:10

Reza Aghaei