问题
I have a pre-configured ListView (with column headers already set up), that I would like to task a list of object, and write - as rows to that listview - specific attributes of the class I have a list of.
I'm trying to follow this existing question, while it perfectly handles an item with only one column, I'm not sure how to apply multiple sub items.
I have a class that contains a List<Product>
which is being handed off to a UserControl that takes that list and adds each product item to a ListView within the control.
While the linked Q&A handles this it's not complete, and I have no idea how to get other attributes into the ListView as SubItems.
My snippet: Products.Items.AddRange(basket.ProductList.Select(p => new ListViewItem(p.Description)).ToArray());
where p
is a List<Product>
I'd like also to have the item quantity, unit price and line total (which is worked out in the class already) in the listview, but I'm not sure where to start.
回答1:
ListViewItem
class has a lot of constructors. The most appropriate for your case is ListViewItem Constructor (String[])
public ListViewItem(string[] items)
Initializes a new instance of the ListViewItem class with an array of strings representing subitems.
With your snippet, something like this
Products.Items.AddRange(basket.ProductList.Select(p => new ListViewItem(new string[]
{
p.Description,
p.Quantity.ToString(...),
p.UnitPrice.ToString(...),
...
})).ToArray());
Note that ListViewItem.Text
is actually ListView.SubItems[0].Text
.
来源:https://stackoverflow.com/questions/34500081/converting-listobject-to-listview-items-with-subitems