我的程序中有以下代码,它抛出索引超出绑定的异常 line yearList.SetValue(years [count],count);
protected void invoiceYear_DataBound(object sender, EventArgs e)
{
//invoiceYear.SelectedItem.Value= GetYearRange();
String[] years = GetYearRange().Split(new char[] { '[', ',', ']',' ' });
ListItem [] yearList = new ListItem[]{};
System.Diagnostics.Debug.WriteLine("years-->" + years.Length);
for (int i = 0; i < years.Length; i++)
{
System.Diagnostics.Debug.WriteLine("years-->" + years.GetValue(i));
}
int count = 0;
foreach (String str in years)
{
if (string.IsNullOrEmpty(str))
System.Diagnostics.Debug.WriteLine("empty");
else
{
yearList.SetValue(years[count], count);
count++;
}
}
//System.Diagnostics.Debug.WriteLine("yearList-->" + yearList.GetValue(0));
//invoiceYear.Items.AddRange(yearList);
}
答案 0 :(得分:7)
你没有问过问题,所以我猜你的问题只是“为什么?”
yearList
被定义为空数组:
ListItem [] yearList = new ListItem[]{};
它的长度始终为零。因此,您无法设置它的任何元素,因为它没有要设置的元素。
<强>更新强>
你现在问:“但我没有得到如何声明动态数组?”
.NET中没有动态数组。根据您的方案,您有许多不同的集合类型。我建议List<ListItem>
可能就是你想要的。
List<ListItem> yearList = new List<ListItem>(); // An empty list
然后
yearList.Add(years[count]); // Adds an element to the end of the list.
或者,整个循环可以更好地写为:
foreach (String str in years)
{
if (string.IsNullOrEmpty(str))
System.Diagnostics.Debug.WriteLine("empty");
else
{
yearList.Add(str);
}
}
然后你不必担心count
,也不会失去一步(因为你只是在str包含某些内容时递增计数 - 这可能不是你想要的)
更新2
如果你最后拼命地需要一个数组,你总是可以使用yearList.ToArray()
将列表转换为数组,但是请记住在文件顶部添加using System.Linq;
,因为它是一个扩展方法, LINQ提供而不是List类本身的一部分。
答案 1 :(得分:0)
为什么要使用Foreach
循环,如果你想保留计数器就可以使用For
?
foreach (var int i = 0; i < years.Length; i++)
{
if (string.IsNullOrEmpty(years[i]))
System.Diagnostics.Debug.WriteLine("empty");
else
{
yearList.SetValue(years[i], i);
}
}
答案 2 :(得分:0)
我不知道您的目标是什么,我对ListItem
没有任何经验,但您是否考虑过这种方法:
string[] yearList = years.Where(y => !string.IsNullOrEmpty(y)).ToArray();
这将创建一个非空或空的所有年份的数组。它还取决于您如何使用列表来确定这是否有用。如果它不需要是一个数组,那么你甚至可以这样做:
var yearList = years.Where(y => !string.IsNullOrEmpty(y));
请注意,这些解决方案与诊断输出或ListItem
的使用完全不同。它还取决于您使用的.net版本是否适合您。