gpt4 book ai didi

c# - 带有列表框的 foreach 的奇怪问题

转载 作者:太空宇宙 更新时间:2023-11-03 19:18:21 25 4
gpt4 key购买 nike

我正在尝试从列表框元素填充组合框。

这是代码:

foreach(string elements in (Application.OpenForms[1] as Impostazioni).listBox1)
{
cbxValuta.Items.Add(elements);
}

但我从 Visual Studio 2012 中收到此错误:

Error 1 foreach statement cannot operate on variables of type 'System.Windows.Forms.ListBox' because 'System.Windows.Forms.ListBox' does not contain a public definition for 'GetEnumerator'

我不知道如何解决这个错误。

最佳答案

如果你想迭代 ListBox 元素,你必须使用 Items属性(property)。

试试这个:

foreach(string elements in (Application.OpenForms[1] as Impostazioni).listBox1.Items)
{
cbxValuta.Items.Add(elements);
}

错误:

But now I get this error: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

首先,您必须检查 Application.OpenForms 是否不为 null 且不为空。

所以在 foreach 之前你必须添加下面一行代码:

如果 Application.OpenForms 是列表:

if(Application.OpenForms != null && Application.OpenForms.Count != 0)

如果 Application.OpenForms 是数组:

if(Application.OpenForms != null && Application.OpenForms.Length != 0)

关于c# - 带有列表框的 foreach 的奇怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14386865/

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