0

I am beginner in c#. This is a small question. I want to add Images to image list with image index.

  ilsLargeFlags  --> ImageList
  strFlagPath --> full file path
  strPetPath  --> only file name (gif image)

I tried the below code: (not working)

 ilsLargeFlags.Images.Add(Image.FromFile(strFlagPath));
 ilsLargeFlags.Images.SetKeyName(8, strPetPath);

what I am doing wrong in the above code?

There are already 8 images in the imageList. added by simple user interface( i dont know what it is said to be)

Mr_Green
  • 40,727
  • 45
  • 159
  • 271

1 Answers1

5

You should better call ImageList.ImageCollection.Add(String, Image). In that case you could provide the key name in one step:

ilsLargeFlags.Images.Add(strPetPath, Image.FromFile(strFlagPath));

Update

By using the ImageList and its internal ImageListCollection you won't be able to set a specific numeric index (hence it does not support IndexOf() method. Instead you use some kind of self-defined string key. If you really need the current index of on image you should use the IndexOfKey() method after adding it to the list with the desired key:

ilsLargeFlags.Images.Add(strPetPath, Image.FromFile(strFlagPath));
var index = ilsLargeFlags.Images.IndexOfKey(strPetPath);

Now it would be possible to change the key name by using the SetKeyName() method and the retrieved index, but this could lead to doubled key names if someone is going to remove images from the list and afterwards you would add another image. So better stick to some key names and get out the corresponding index at the moment you'll need it by calling IndexOfKey().

Oliver
  • 43,366
  • 8
  • 94
  • 151
  • The image is not added to imageList. I think the above code is not even giving imageIndex to the current image. am I wrong? – Mr_Green Oct 22 '12 at 08:13
  • Doesnt the computer itself generates the image key in a sequential way? For example: if I add a image to imagelist which has already three images in it then the newly added image should have the image index of 3 (4-1 = 3)? If it happens in sequential way automatically then it solves my problem. I am trying it now.. – Mr_Green Oct 22 '12 at 12:15
  • @Mr_Green: The two accessing methods (by key or by index) of the ImageList are existing next to each other. So if you remove the first image of the list all other images get a new index (cause their will never be any holes within the index sequence). The key won't be affected it will be constant till you explicitly change it by calling `SetKeyName()`. – Oliver Oct 22 '12 at 12:19
  • I forgot to +1 you at that time. this is really very useful info for me. – Mr_Green Nov 07 '12 at 05:19