Reputation: 3505
I am new to WinForms and I can't understand how to add my additional data to a ListViewItem
? I remember that in MFC, I can use SetItemDataPtr
but how to do this in WinForms?
Upvotes: 2
Views: 1998
Reputation: 6159
The most recommended method would be to create your own class, deriving from ListViewItem
, and add instances of this class to the ListView
. This way you can store any data in the items.
This is better than using the Tag
property, because of several reasons:
Tag
property free to be used by potential future extensions.Upvotes: 6
Reputation: 1974
One of the way: you need to create your own class, for example, MyItem
and put you items in List<MyItem>
. Then use data binding. Class MyItem
should implement ToString()
method that returns string will be displayed in ListView.
Upvotes: 0
Reputation: 941635
You can use the ListViewItem.Tag property to store a reference to any object, the equivalent of SetItemDataPtr(). The Name property can be handy to act as a key in a Dictionary<>. And the Index property could be useful to index a List<>. The latter two approaches are the better solutions, you normally want to keep the data separate from the view.
Upvotes: 2
Reputation: 24713
Have you looked on MSDN for the ListViewItem class? There is a wealth of information there along with samples.
// Create three items and three sets of subitems for each item.
ListViewItem item1 = new ListViewItem("item1",0);
// Place a check mark next to the item.
item1.Checked = true;
item1.SubItems.Add("1");
item1.SubItems.Add("2");
item1.SubItems.Add("3");
ListViewItem item2 = new ListViewItem("item2",1);
item2.SubItems.Add("4");
item2.SubItems.Add("5");
item2.SubItems.Add("6");
ListViewItem item3 = new ListViewItem("item3",0);
// Place a check mark next to the item.
item3.Checked = true;
item3.SubItems.Add("7");
item3.SubItems.Add("8");
item3.SubItems.Add("9");
Upvotes: 2