Domanda

I have a listview with an imagelist so I can show pictures near text in a listview.

The problem is that the application re-downloads a new picture every time you press the button, so that means it deletes the previous downloaded picture.  

How can this be avoided?

    try
    {
        var req = WebRequest.Create(string.Format("http://minotar.net/avatar/{0}/24.png", textBox1.Text));
        var stream = req.GetResponse().GetResponseStream();
        var img = Image.FromStream(stream);
        var imageList1 = new ImageList();
        pictureBox1.Image = img;

        imageList1.Images.Add(Image.FromFile(img2));
        listView1.SmallImageList = imageList1;

        for (int _index = 0; _index < imageList1.Images.Count; _index++)
        {
            var item = new ListViewItem();
            item.ImageIndex = _index;
            listView1.Items.Add(item).Text = " " + textBox1.Text;
        }
    }
    catch (Exception)
    {
        pictureBox1.Image = Properties.Resources._200;
    }
È stato utile?

Soluzione

Create a cache - and check to see if you already have it. If the images don't change, you can change it to caching to disk (image.Save) instead.

// Class-level variable
var _imageDictionary = new Dictionary<string,Image>();


// Logic in method
Image image;
if(_imageDictionary.ContainsKey(textBox1.Text))
 image = _imageDictionary[textBox1.Text];
else {
   image = // code to retrieve image from web
   _imageDictionary[textBox1.Text] = image;
}

// ... add it to your image list
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top