“IndexOutOfRangeException:索引在数组之外."发生异常 [英] "IndexOutOfRangeException: Index was outside of the array." exception occured

查看:91
本文介绍了“IndexOutOfRangeException:索引在数组之外."发生异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在设置ImageList的ImageCollection的SetKeyName方法时遇到了这个异常.

I encountered this exception while setting the SetKeyName method of ImageCollection of ImageList.

 this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
        this.imageList1.TransparentColor = System.Drawing.Color.Fuchsia;
        this.imageList1.Images.SetKeyName(0, "");
        this.imageList1.Images.SetKeyName(1, "");

我也在我的主表单中使用了这个imageList1.ImageStream",它在那里工作得很好.我被困在这里,我不知道这个问题究竟是什么,它是如何提出的,我该如何解决这个问题.

i have used this "imageList1.ImageStream" in my Main Form too, and it works fine there. I am stuck here and i do not know what actually this issue is, how it raised and how can i solve this.

任何建议和意见将不胜感激.谢谢!!

Any suggestions and comments will be much appreciated. Thank you!!

推荐答案

最有可能的这一行:

this.imageList1.Images.SetKeyName(1, "");

导致您的异常.当然,它也可以是索引为 0 的第一行.基本上,例外是说代码在尝试访问给定索引处的数组时失败.原因是该数组在该索引处没有项目.

Is causing your exception. Of course it could also be the first line with Index 0. Basically the exception is saying that code failed while trying to access the array at a given index. The reason being that the array doesn't have an item at that index.

例如,在您的情况下,代码假定数组中有 2 个项目.一个在索引 0 和一个在索引 1.如果数组只有一项,第二行将失败并抛出异常.

For example in your case the code assumes that there are 2 items in the array. One at index 0 and one at index 1. If the array has only one item the second line will fail and throw the exception.

在尝试对其执行任何操作之前,您所要做的就是确保在给定索引处有一个项目.

All you have to do is make sure you have an item at a given index before you try to perform any operations on it.

类似:

if(this.imageList1.Images.Count >= 2)
{
   this.imageList1.Images.SetKeyName(1, "");
}

这篇关于“IndexOutOfRangeException:索引在数组之外."发生异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆