gpt4 book ai didi

c# - 带有 foreach 的 IndexOutOfRangeException

转载 作者:太空狗 更新时间:2023-10-29 23:32:46 25 4
gpt4 key购买 nike

编辑:查看底部以了解发生这种情况的中途原因

我有一个非常奇怪的 IndexOutOfRangeException(如标题所述)。当我使用 foreach 遍历控件的控件(递归 FindControl)时会发生这种情况。

strange error 1

然后我想添加一个额外的检查来确保 root.Controls.Count > 0。但是,我不断收到异常,而调试器清楚地显示 Count == 0

strange error 2

有问题的根是 FormView。如果有人知道为什么简单的属性检查会抛出 IndexOutOfRangeException,请赐教!

异常堆栈跟踪(是的,它是完整的):

   at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)

代码:

public static Control FindControlRecursive(this Control root, string id)
{
if (root.ID == id)
{
return root;
}

if (root.Controls.Count > 0)
{
foreach (Control c in root.Controls)
{
Control t = c.FindControlRecursive(id);
if (t != null)
{
return t;
}
}
}

return null;
}

编辑:

我尝试使用 native FindControl 函数,这会引发相同的相同错误。


具体问题:

foreach 如何在 native 集合上抛出 IndexOutOfRangeException。


编辑 2:

不知何故,这似乎与使用 ObjectDataSource 有关,我没有正确填写输入参数,但我没有收到任何错误。也许这以某种方式损坏了 FormView(正在使用该数据源)。我仍然很想知道在访问子控件之前如何在不抛出错误的情况下发生这种情况。

最佳答案

而不是 Controls.Count,尝试使用 Control.HasControls() , 可能会解决这个问题。

关于c# - 带有 foreach 的 IndexOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14396520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com