Sanja Melnichuk
Sanja Melnichuk

Reputation: 3505

Adding additional data to a WinForms ListViewItem

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

Answers (4)

Ran
Ran

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:

  • Your item data can be type-safe, and you won't have to cast from Object on each access.
  • You can store more than one value.
  • It is more correct in terms of object oriented programming.
  • You leave the Tag property free to be used by potential future extensions.

Upvotes: 6

DReJ
DReJ

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

Hans Passant
Hans Passant

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

Aaron McIver
Aaron McIver

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

Related Questions