C# foreach与listbox的奇怪问题

C# foreach与listbox的奇怪问题,c#,winforms,combobox,listbox,C#,Winforms,Combobox,Listbox,我正在尝试从listbox元素填充combobox 这是代码: foreach(string elements in (Application.OpenForms[1] as Impostazioni).listBox1) { cbxValuta.Items.Add(elements); } 但我从Visual Studio 2012中得到了以下错误: 错误1 foreach语句无法对类型为的变量进行操作 “System.Windows.

我正在尝试从listbox元素填充combobox

这是代码:

foreach(string elements in (Application.OpenForms[1] as Impostazioni).listBox1)
        {
            cbxValuta.Items.Add(elements);
        }
但我从Visual Studio 2012中得到了以下错误:

错误1 foreach语句无法对类型为的变量进行操作 “System.Windows.Forms.ListBox”是因为“System.Windows.Forms.ListBox” 不包含“GetEnumerator”的公共定义


我不知道如何解决此错误。

如果要在列表框元素上迭代,必须使用属性

试试这个:

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

但现在我得到了这个错误:索引超出了范围。必须是非负的 并且小于集合的大小。参数名称:索引

首先,您必须检查Application.OpenForms是否为空

因此,在foreach之前,必须添加以下代码行:

如果Application.OpenForms是列表:

if(Application.OpenForms != null && Application.OpenForms.Count != 0)
如果Application.OpenForms是数组:

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

若要在ListBox元素上迭代,则必须使用属性

试试这个:

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

但现在我得到了这个错误:索引超出了范围。必须是非负的 并且小于集合的大小。参数名称:索引

首先,您必须检查Application.OpenForms是否为空

因此,在foreach之前,必须添加以下代码行:

如果Application.OpenForms是列表:

if(Application.OpenForms != null && Application.OpenForms.Count != 0)
如果Application.OpenForms是数组:

if(Application.OpenForms != null && Application.OpenForms.Length != 0)
如果您想在代码中使用,您的类应该实现或接口

尝试使用
.Items
属性。喜欢

(Application.OpenForms[1] as Impostazioni).listBox1.Items
如果您想在代码中使用,您的类应该实现或接口

尝试使用
.Items
属性。喜欢

(Application.OpenForms[1] as Impostazioni).listBox1.Items

检查
listBox1
是否有可以枚举的
.Items
属性。

检查
listBox1
是否有可以枚举的
.Items
属性。

您需要从listBox1获取“Items”集合,而不是使用整个列表框

foreach(string elements in (Application.OpenForms[1] as Impostazioni).listBox1.Items)
    {
        cbxValuta.Items.Add(elements);
    }
您需要从listbox1获取“Items”集合,而不是使用整个listbox

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

好的,谢谢。但现在我得到了这个错误:索引超出了范围。必须为非负数且小于集合的大小。参数名称:indexdone,谢谢。但现在我得到了这个错误:索引超出了范围。必须为非负数且小于集合的大小。参数名称:索引