Luke
Luke

Reputation: 23680

Adding items to list view with text label and key value

I'm trying to add items to a ListView control. I wish to add the items with a text value (which is shown) and a hidden key value that it has when it is selected.

I've tried the following code:

string flows_path = "C:\\temp\\Failed Electricity flows\\";
            List<ListViewItem> flows_loaded = new List<ListViewItem>();

            foreach (string s in Directory.GetFiles(flows_path, "*.rcv").Select(Path.GetFileName))
            {
                ListViewItem new_item = new ListViewItem(s, 1);
                ListViewItem.ad

                // Add the flow names to the list
                flows_loaded.Add(new_item);

            }

But it tells me that ListViewItem doesn't have an overload of (string, int) and it doesn't appear to have a 'value', 'text' or 'key' value that I can set.

ListViewItem("My Item") works, but I don't know how to implement a key for each item.

Upvotes: 4

Views: 8509

Answers (3)

Tsad
Tsad

Reputation: 1

ListView has item key functionality you want. You can add key to the item this way:

listView1.Items.Add("yourKey", "itemText", imageIndex);

but if you want to add to ListView by ListViewItem object, the object constructor doesn't have key parameter for item. You can then use Name property (which is the item key property in fact).

ListViewItem new_item = new ListViewItem("itemText", imageIndex){ Name = "yourKey"};

// Add the flow names to the list
flows_loaded.Add(new_item);

Upvotes: 0

John Willemse
John Willemse

Reputation: 6698

You can store an additional value associated with a ListViewItem by storing it in the Tag property.

ListViewItem new_item = new ListViewItem(s);
new_item.Tag = my_key_value;

ETA: Please remember that the Tag property is of type object, so in some cases you may need to explicitly cast values to the proper type when retrieving the value.

Upvotes: 8

Tomtom
Tomtom

Reputation: 9394

You can add a "hidden"-value by setting the Tag-Property of the ListViewItem

ListViewItem new_item = new ListViewItem(s)
{
   Tag = 1
};

Upvotes: 3

Related Questions