Is it possible to set listbox datasource to List<Tuple<string, string, int>> Item1 only?

点点圈 提交于 2019-12-12 04:37:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!