我对 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=“-1”的值对于“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)'
我应该怎样做呢?有替代方法的建议吗?
提前致谢。
最佳答案
只需使用
imageList1.Images[comboBox1.SelectedItem.ToString()];
删除任何断点或消息框
关于c# - 如何按名称而不是位置索引图像列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27826992/