如何按名称而不是位置索引图像列表?

时间:2015-01-07 19:19:06

标签: c# combobox windows-forms-designer imagelist

我是C#的新手,正在使用Windows 7上的Visual Studios Express 2012.

我有一个名为"a""b""c"的图片的图像列表,我有一个包含选项"a""b"的组合框,和"c"

我尝试将与组合框选择对应的图像添加到图片框中。

最初我使用的是位置,而不是这样的名字:

         int i = comboBox1.SelectedIndex;
         pictureBox1.Image = imageList1.Images[i];

但是,我认为以后可能会对组合框选项进行更改,它们可能不再是相同的顺序,所以我想按名称而不是位置来进行。

我试过了:

         string name = comboBox1.SelectedText;
         int i = imageList1.Images.IndexOfKey(name);
         pictureBox1.Image = imageList1.Images[i];

但这会导致运行时错误System.ArgumentOutOfRangeException ... InvalidArgument=Value of '-1' is not valid for 'index'

我也在想这样的事情可能有用:

         string grade = comboBox1.SelectedText;
         pictureBox1.Image = imageList1.ImageCollection.IndexOfKey(grade); 

         pictureBox1.Image = ImageList.ImageCollection.IndexOfKey(grade); 

但是这些给我编译错误

'ImageCollection': cannot reference a type through an expression; 
 try 'System.Windows.Forms.ImageList.ImageCollection'

An object reference is required for the non-static field, method, or property 
'System.Windows.Forms.ImageList.ImageCollection.IndexOfKey(string)'

我应该怎么做呢?对替代方法的建议?

提前致谢。

2 个答案:

答案 0 :(得分:1)

只需使用

imageList1.Images[comboBox1.SelectedItem.ToString()]; 

删除任何断点或消息框

答案 1 :(得分:1)

我尝试过Tuco的解决方案并最终出现了同样的错误。

通过尝试我找到了我的解决方案......所以我为所有没有用给定解决方案解决问题的人提供这个。

就我而言,它是一个名为tvFiles

的Treeview
/* Fill/Define the TreeViews ImageList */
tvFiles.ImageList   = imageList1;
/* Set the Index by Imagename */
tvFiles.ImageIndex  = imageList1.Images.IndexOfKey(imgName);