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

标签 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=“-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/

相关文章:

mysql - 所有值未显示在组合框中

c# - 为什么 ListView 的 OnDrawItem 事件不影响设计时环境?

c# - 如何更新到数据库

c# - 配置 DataGridView 的 'AutoGenerateColumns' 属性

c# - 仅使用 DropDown 进行 DateTimePicker 选择

apache-flex - 如何删除组合框中已选择的项目

c# - 如果无法设置转换器参数,IValueConverter 保持状态

C# 如果在组合框 winform 中选择了某些文本

c# - 使用 TimeSpan.ParseExact 解析时,输入字符串的格式不正确

c# - Paypal express 错误 "The totals of the cart item amounts do not match order amounts"