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:
How can I accomplish this?
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With