开发者

want to avoid duplicate images in listview C# .NET

I am using imagelist with listview component for the firs time, what i wanted is to list images. the problem i am facing is i couldn't avoid duplicate images while adding images again 开发者_运维技巧to listview. please see following code and let me know where i am going wrong

OpenFileDialog addImages = new OpenFileDialog();
        addImages.Filter = "JPEG (*.jpg)|*.jpg";
        addImages.Multiselect = true;
        if (addImages.ShowDialog(this) == DialogResult.OK)
        {
            foreach (string filename in addImages.FileNames)
            {
                try
                {
                    if (this.imageList1.Images.ContainsKey(filename) == false)
                    {
                        this.imageList1.Images.Add(filename, Image.FromFile(filename));
                    }
                }
                catch{}
            }
            this.listView1.View = View.LargeIcon;
            this.listView1.LargeImageList = this.imageList1;

            for (int i = 0; i < this.imageList1.Images.Count; i++)
            {
                if (this.listView1.Items.ContainsKey(this.imageList1.Images.Keys[i]) == false)
                {
                    ListViewItem li = new ListViewItem();
                    li.ImageIndex = i;
                    li.ImageKey = this.imageList1.Images.Keys[i];
                    li.Text = Path.GetFileName(this.imageList1.Images.Keys[i]);
                    this.listView1.Items.Add(li);
                }
            }
        }


You used the function "ContainsKey" for duplicate.

this.listView1.Items.ContainsKey()

MSDN say : " The Name property corresponds to the key for a ListViewItem in the ListView.ListViewItemCollection."

So you need to set the name of your ListViewItem.


I don't fully understand your question, but there are a few things that you could do.

  1. add a this.listView1.Items.Clear() in the function, before the for-loop. Next time you open the OpenFileDialog you will add items to an empty listview.

  2. add the filename in each LiveViewItem tag. li.Tag = ...filepath.... Then every time you add a new item to the listView, just check if it doesn't already contain an item with that tag.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜