Vin*_*alo 1 c# combobox listbox winforms
我正在尝试从列表框元素中填充组合框.
这是代码:
foreach(string elements in (Application.OpenForms[1] as Impostazioni).listBox1)
{
cbxValuta.Items.Add(elements);
}
Run Code Online (Sandbox Code Playgroud)
但我从Visual Studio 2012得到此错误:
错误1 foreach语句无法对"System.Windows.Forms.ListBox"类型的变量进行操作,因为"System.Windows.Forms.ListBox"不包含"GetEnumerator"的公共定义
我不知道如何解决这个错误.
如果要迭代ListBox元素,则必须使用Items属性.
试试这个:
foreach(string elements in (Application.OpenForms[1] as Impostazioni).listBox1.Items)
{
cbxValuta.Items.Add(elements);
}
Run Code Online (Sandbox Code Playgroud)
错误:
但是现在我收到了这个错误:索引超出了范围.必须是非负数且小于集合的大小.参数名称:index
首先,您必须检查Application.OpenForms是否为空且不为空.
因此,在foreach之前,您必须添加以下代码行:
如果Application.OpenForms是列表:
if(Application.OpenForms != null && Application.OpenForms.Count != 0)
Run Code Online (Sandbox Code Playgroud)
如果Application.OpenForms是数组:
if(Application.OpenForms != null && Application.OpenForms.Length != 0)
Run Code Online (Sandbox Code Playgroud)