Reputation: 87
So, trying to use the ListView and fill it with data.
ListViewItem item = new ListViewItem("Test");
item.SubItems.Add("1");
item.SubItems.Add("2");
MyListView.Items.Add(item);
Now, I haven been searching and reading and I feel so stupid cause I just can't figure out how the items/subitems work.
The above code won't do anything :/
foreach (Ingredient o in list) { ListViewItem lvi = new ListViewItem(); lvi.Text = o.iName; lvi.SubItems.Add(o.iUnit); lvi.SubItems.Add(Convert.ToString(o.iCalories)); listView1.Items.Add(lvi); }
It works now, BUT, I no longer have access to the items. How do I know get back an item, or change stuff in an item?
Upvotes: 0
Views: 15197
Reputation: 87
listView1.Items.Clear();
listView1.View = View.Details;
List<Ingredient> list = controller.FindAllIngredients();
foreach (Ingredient o in list)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = o.iName;
lvi.SubItems.Add(o.iUnit);
lvi.SubItems.Add(Convert.ToString(o.iCalories));
listView1.Items.Add(lvi);
}
How do I make this into a generic method that doesn't have to know the number of fields. For example, if i added another field, Category to Ingridient this method wouldn't work. Would also like to use it for all my listviews, independ on the class and number of columns.
Upvotes: 1
Reputation: 722
This should work:
viewList.View = View.Details;
viewList.Columns.Add("Key");
viewList.Columns.Add("Value");
ListViewItem lvi1 = new ListViewItem();
lvi1.Text = "Key";
lvi1.SubItems.Add("Value");
viewList.Items.Add(lvi1);
Upvotes: 2
Reputation:
In your ListView
control, you need to set the View
style to Details if you want to see the SubItems
.
Example:
MyListView.View = View.Details;
Upvotes: 0
Reputation: 5439
Each subitem is a column in the ListView. Due to this, myListView
needs to have 3 columns configured based on the above code.
In your example above, Test
would be in the first column, 1
in the second, and 2
in the third.
Upvotes: 0