Store string lists in separate columns of a listview (C#)
Hope I can do this, I'm still newish to C#...
I have a bunch of lists of strings that I want to put into different columns of a Lis开发者_如何学JAVAtview. I'm able to get the first column to populate using the code shown below, but can't figure out how to do this for the subsequent columns.
List<string> l_Time = new List<string>();
//l_Time is populated by a method
foreach (string elem in l_Time)
{
listViewEvents.Items.Add(new ListViewItem(elem));
}
listViewEvents is my ListView
Any help is appreciated.
Edit:
Both shown solutions work to store my lists across a row, which I was able to find a lot online. I want to be able to store each list down it's own column. Is this possible?
Try this:
listViewEvents.Items.Add(new ListViewItem(l_Time.ToArray()));
The ListViewItem
class has a constructor that takes an array of strings. When that constructor is used, then the other strings will appear in the other columns.
If you want to do more with the other columns, then the list view item has a SubItems
property that holds a collection of ListViewItem.ListViewSubItem
objects. You can create these with whatever values you want and add them to the list view item objects.
UPDATE
Here's a way to display lists of strings in separate columns:
private static void DisplayListInColumns(ListView listView, List<string> values, int columnIndex)
{
for (int index = 0; index < values.Count; index++)
{
while (index >= listView.Items.Count)
listView.Items.Add(new ListViewItem());
ListViewItem listViewItem = listView.Items[index];
while (listViewItem.SubItems.Count <= columnIndex)
listViewItem.SubItems.Add(new ListViewItem.ListViewSubItem());
listViewItem.SubItems[columnIndex].Text = values[index];
}
}
Called like this:
List<string> listOne = new List<string>() { "one", "two", "three", "four", "five", "six" };
List<string> listTwo = new List<string>() { "January", "February", "March", "April", "May" };
List<string> listThree = new List<string>() { "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel" };
DisplayListInColumns(myListView, listOne, 0);
DisplayListInColumns(myListView, listTwo, 1);
DisplayListInColumns(myListView, listThree, 2);
Sure it's possible. Assuming all your lists have the same length, just go through the first list one item at a time, and for each item, add to SubItems
the element from every other list with the same index. In other words, add the item at index 0 from every list to one ListView item, then the item at index 1 from every list to another ListView item, and so on.
Try something along those lines:
// This assumes all lists have the sample number of items
for (int i = 0; i < list1.Count; i++)
{
ListViewItem lvi = new ListViewItem(list1[i]);
lvi.SubItems.Add(list2[i]);
lvi.SubItems.Add(list3[i]);
listViewEvents.Items.Add(lvi);
}
精彩评论