C# 发生异常

C# 发生异常,c#,C#,我总是犯同样的错误 An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll Additional information: InvalidArgument=Value of '0' is not valid for 'index'. 代码是: private void radGridView1_CellFormatting(object s

我总是犯同样的错误

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll 
Additional information: InvalidArgument=Value of '0' is not valid for 'index'.
代码是:

private void radGridView1_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e)
    {
        if (e.CellElement.ColumnInfo.HeaderText == "logo")
        {
            if (e.CellElement.RowInfo.Cells[2].Value.ToString() == "Error")
            {
                e.CellElement.Image = (Image)imageList1.Images[0];
                e.CellElement.ToolTipText = "Error";
            }
            else if (e.CellElement.RowInfo.Cells[2].Value.ToString() == "Warning")
            {
                e.CellElement.Image = imageList1.Images[1];
                e.CellElement.ToolTipText = "Warning";
            }
            else if (e.CellElement.RowInfo.Cells[2].Value.ToString() == "Message")
            {
                e.CellElement.Image = imageList1.Images[2];
                e.CellElement.ToolTipText = "Message";
            }
        }
    }
    }

//------------------------------------

从外观上看,阵列中没有任何内容。检查索引是否已实际初始化,然后继续操作。

MSDN这样说

当参数值超出被调用方法定义的允许值范围时引发的异常

关于这个问题。它接着说

您正在按索引号检索集合的成员,而索引号无效

这是ArgumentOutOfRange异常最常见的原因 例外通常,索引编号对于三个索引中的一个无效 原因:

集合没有成员,代码假定它有成员

您正在尝试检索索引为负的项。这 通常发生,因为您已在集合中搜索 特定元素和错误地假设搜索是 成功

您正在尝试检索其索引等于 集合的Count属性的值

我怀疑这是这里的第一个案例,即imageList1为空。因此,您的imageList1.Images[0]抛出异常,因为那里没有任何内容


要确定是否是这种情况,请尝试imageList1.Images.Count。如果您正在查看代码中的3个元素,则计数必须大于等于3。

听起来像imageList1。图像可能是空的。您至少检查过了吗?如果您可以将异常作为文本发布会更好。@AliHassanQureshi在引发异常时它似乎是空的。您看到的图像可能来自另一个图像列表,或者您可能正在清除或替换imageList1.images。请在radGridView1\u CellFormatting的第一行上放置断点,并在调试器中运行。当调试器停在那里时,检查“监视”窗口中的imageList1.Images.Count以查看有多少图像。不需要猜测。@kiziu所以有一个未知的实体,它有一个表单设计器自动生成的名称,它有一个Images属性,编译器认为可以用整数索引它,但是如果在运行时用整数索引它,它会抛出ArgumentOutOfRangeException。BRB,我得喂我的独角兽。那imageList是什么类型的?你能提供一个例子来证明这一点吗?基本上,没有更多的信息,我们只是猜测。这不是一个答案,这是一个重复了几个现有评论的评论。我已经这样做了。图像计数为4。如果列表为空,那么如何在winform上显示图像。