4

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.

1
  • 1
    You could use the Tag property of every ListViewItem to store and retrieve the key value. Commented Mar 5, 2013 at 11:07

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

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

2 Comments

Thanks. Am I using the wrong control type if I have to use the Tag, or is this the correct way to implement this?
It's the correct way. The Tag-Property you have at each control. There you can save any informations you'll need.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.