每个列表框都有一个奇怪的问题
本文关键字:问题 有一个 列表 | 更新日期: 2023-09-27 17:54:29
我正在尝试从列表框元素填充组合框。
这是代码:
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'的公共定义
我不知道如何解决这个错误
如果你想遍历ListBox元素,你必须使用Items属性。
试试这个:
foreach(string elements in (Application.OpenForms[1] as Impostazioni).listBox1.Items)
{
cbxValuta.Items.Add(elements);
}
错误:
但是现在我得到这个错误:索引超出范围。必须是非负的而且比藏品的大小还小。参数名称:index
首先你必须检查是否应用程序。OpenForms不是空的,也不是空的
所以在foreach之前必须添加以下代码行:
如果应用程序。OpenForms is list:
if(Application.OpenForms != null && Application.OpenForms.Count != 0)
如果应用程序。OpenForms是数组:
if(Application.OpenForms != null && Application.OpenForms.Length != 0)
如果你想在代码中使用foreach
,你的类应该实现IEnumerable
或IEnumerable<T>
接口。
尝试.Items
属性。
(Application.OpenForms[1] as Impostazioni).listBox1.Items
检查listBox1
是否有可以枚举的.Items
属性
您需要从listbox1中获取"Items"集合,而不是使用整个listbox。
foreach(string elements in (Application.OpenForms[1] as Impostazioni).listBox1.Items)
{
cbxValuta.Items.Add(elements);
}