【问题标题】:"IndexOutOfRangeException: Index was outside of the array." exception occured“IndexOutOfRangeException:索引在数组之外。”发生异常
【发布时间】:2014-02-05 06:41:54
【问题描述】:

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

 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”,它在那里工作得很好。我被困在这里,我不知道这个问题到底是什么,它是如何产生的以及我该如何解决这个问题。

任何建议和 cmets 将不胜感激。谢谢!!

【问题讨论】:

  • 您确定您的班级可以使用该资源吗?所有这些错误意味着您正在尝试将键名设置为不存在的值。显然,找不到您的 imageList1
  • 在调用 SetKeyName() 之前确保 ImageList 中有 2 个图像

标签: c# .net winforms visual-studio-2010 runtime-error


【解决方案1】:

试试这个:

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

【讨论】:

  • 逻辑上你是对的,我也同意这一点。但这不起作用,因为我在第一条语句中已经遇到问题 this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));异常 System.Reflection.TargetInvocationException:调用的目标已引发异常。 ---> System.InvalidOperationException: ImageList 的加载没有成功。
  • @user2991876 好的。这个错误是一个单独的问题。如果您提出新问题,我们很乐意帮助您解决问题:)
【解决方案2】:

很可能是这一行:

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

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

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

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

类似:

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

【讨论】:

  • 请参阅@rhughes 的回答,以获得更好的处理列表的方法。在这种情况下,for 循环非常有用。
猜你喜欢
  • 2019-04-07
  • 1970-01-01
  • 2012-06-05
  • 2013-04-19
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多