问题
I have
public static class GlobalVariables
{
public static List<Tuple<string, string, int>> PopFile;
}
and I'm trying to use PopFile as a datasource to listbox
listBox1.DataSource = GlobalVariables.PopFile;
The problem is that it obviously adds ([string], [string], [int]) to the listbox but I want to add only the first items of tuples. Is that possible?
I could use
foreach (Tuple<string, string, int> i in GlobalVariables.PopFile)
{
listBox1.Items.Add(i.Item1);
}
but I'd prefer .DataSource.
回答1:
listBox1.DataSource = GlobalVariables.PopFile;
listBox1.DisplayMember = "Item1";
listBox1.ValueMember = "Item3"; // optional
https://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.datasource
回答2:
In the end, you can't really avoid looping through and either individually adding your data from your tuple object or creating a new object to bind to the listbox.
Listbox simply doesn't have the input parameters to take in a tuple object unless you extend the Listbox object yourself to be able to handle it appropriately, but even then you will still have to do something similar to your loop above.
回答3:
LINQ might come in handy...
listBox1.DataSource = GlobalVariables.PopFile.Select(t => t.Item1).ToList()
来源:https://stackoverflow.com/questions/45555932/is-it-possible-to-set-listbox-datasource-to-listtuplestring-string-int-ite