Domanda

C#'s ListView has the follow add methods available for adding an entry

public virtual ListViewItem Add(ListViewItem value)
public virtual ListViewItem Add(string text)
public virtual ListViewItem Add(string text, int imageIndex)
public virtual ListViewItem Add(string text, string imageKey)
public virtual ListViewItem Add(string key, string text, int imageIndex)
public virtual ListViewItem Add(string key, string text, string imageKey)

Scenario: I have a ListView and wish to dynamically add ListViewItems with their own unique images in the first column. Furthermore these images can be updated depending upon state changes

Question: How would you do you do this?

Code I'm working with

        private void AddToMyList(SomeDataType message)
        {
            string Entrykey = message.ID;

            //add its 1 column parameters
            string[] rowEntry = new string[1];
            rowEntry[0] = message.name;

            //make it a listviewItem and indicate its row
            ListViewItem row = new ListViewItem(rowEntry, (deviceListView.Items.Count - 1));

            //Tag the row entry as the unique id
            row.Tag = Entrykey;

            //Add the Image to the first column
            row.ImageIndex = 0;

            //Add the image if one is supplied
            imagelistforTypeIcons.Images.Add(Entrykey, message.marker.markerIcon);

            //finally add it to the device list view
            typeListView.Items.Add(row);

        }
È stato utile?

Soluzione

There are two things you need to do

  • Add image to ImageList if it isn't already in it
  • Create new ListViewItem and assign image from previous point to it

It could go like this, based on your code:

// Add markerIcon to ImageList under Entrykey
imagelistforTypeIcons.Images.Add(Entrykey, message.marker.markerIcon);
// Use icon from ImageList which is stored under Entrykey
ListViewItem row = new ListViewItem(rowEntry);
row.ImageKey = Entrykey;
// Do whatever else you need afterwards
row.Tag = Entrykey;
....

Problem with code in your question (without actually trying it out) looks to be in ImageIndex you are assigning.

  • you are adding new image to one image list, but assigning an image to ListViewRow from a different one
  • you are providing image index in constructor but setting it to 0 afterwards (why?)
  • you are providing wrong image index in the first place, because you calculated index of last image in the image list, before adding the new image.

So your code could also be fine like this:

// Add markerIcon to ImageList under Entrykey
imagelistforTypeIcons.Images.Add(Entrykey, message.marker.markerIcon);
// Use icon from ImageList which is stored under Entrykey
ListViewItem row = new ListViewItem(rowEntry);
row.ImageIndex = imagelistforTypeIcons.Items.Count - 1;
// Do whatever else you need afterwards
row.Tag = Entrykey;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top