如何使用图像索引将图像添加到imageList

Mr_*_*een 0 .net c# imagelist

我是c#的初学者.这是一个小问题.我想用图像索引将图像添加到图像列表.

  ilsLargeFlags  --> ImageList
  strFlagPath --> full file path
  strPetPath  --> only file name (gif image)
Run Code Online (Sandbox Code Playgroud)

我尝试了下面的代码:( 不工作)

 ilsLargeFlags.Images.Add(Image.FromFile(strFlagPath));
 ilsLargeFlags.Images.SetKeyName(8, strPetPath);
Run Code Online (Sandbox Code Playgroud)

我在上面的代码中做错了什么?

imageList中已有8个图像.通过简单的用户界面添加(我不知道它是什么)

Oli*_*ver 5

你最好打个电话ImageList.ImageCollection.Add(String, Image).在这种情况下,您可以一步提供密钥名称:

ilsLargeFlags.Images.Add(strPetPath, Image.FromFile(strFlagPath));
Run Code Online (Sandbox Code Playgroud)

更新

通过使用ImageList它及其内部,ImageListCollection你将无法设置特定的数字索引(因此它不支持IndexOf()方法.而是使用某种自定义的字符串键.如果你真的需要图像的当前索引,你应该使用IndexOfKey()所需的密钥将其添加到列表后使用该方法:

ilsLargeFlags.Images.Add(strPetPath, Image.FromFile(strFlagPath));
var index = ilsLargeFlags.Images.IndexOfKey(strPetPath);
Run Code Online (Sandbox Code Playgroud)

现在可以通过使用SetKeyName()方法和检索到的索引来更改密钥名称,但如果有人要从列表中删除图像,之后您可能会添加另一个图像,这可能会导致密钥名称加倍.因此,最好坚持使用一些关键名称,并在您需要时通过调用获取相应的索引IndexOfKey().