“IndexOutOfRangeException: Index was outside of the array.” exception occured

坚强是说给别人听的谎言 提交于 2020-01-06 14:08:14

问题


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, "");

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!!


回答1:


Try this:

this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Fuchsia;

for (int i = 0; i < this.imageList1.Images.Count; i++)
    this.imageList1.Images.SetKeyName(i, "");



回答2:


Most likely this line :

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

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.

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.

Something like :

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


来源:https://stackoverflow.com/questions/21570313/indexoutofrangeexception-index-was-outside-of-the-array-exception-occured

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!