I have the following code in my program which is throwing index out of bound exception at
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);
}
You haven’t asked a question, so I’m going to guess your question is simply “Why?”
yearListis defined as an empty array:It’s length is always zero. Therefore you cannot set any elements of it, as it has no elements to set.
UPDATE
You’ve now asked: “But I am not getting how to declare a dynamic array??”
There are no dynamic arrays in .NET. You have a number of different collection types depending on your scenario. I’ll suggest that
List<ListItem>is probably what you want.Then
Alternatively, that whole loop could be better written as:
Then you are not having to worry about the
countand nor are you getting out of step (because you are only incrementing count when str contains something – which is probably not what you want)UPDATE 2
And if you desperately do need an array at the end, you can always covert the list to an array using
yearList.ToArray(), but remember to addusing System.Linq;at the top of your file as it is an extension method that LINQ provides and not part of the List class itself.