0

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);
        }
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Naga
  • 812
  • 2
  • 8
  • 12
  • You haven't actually asked a question. You might like to update your post to include a question. – Colin Mackay Oct 25 '12 at 22:34
  • Have you tried debugging to see what the value of **count** is when you use it to access the *years* array? – Jamie Keeling Oct 25 '12 at 22:34
  • it is throwing this exception in the first loop itself..means count=0; I gues, its the problem with its declaration "ListItem [] yearList = new ListItem[]{};" I guess its initialized to 0 index. But I am not getting how to declare a dynamic array?? or could be something else too..But I am not able to figure it out.. – Naga Oct 25 '12 at 22:36
  • Does this answer your question? [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Liam Sep 28 '20 at 09:46

3 Answers3

7

You haven't asked a question, so I'm going to guess your question is simply "Why?"

yearList is defined as an empty array:

ListItem [] yearList = new ListItem[]{};

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.

List<ListItem> yearList = new List<ListItem>(); // An empty list

Then

yearList.Add(years[count]); // Adds an element to the end of the list.

Alternatively, that whole loop could be better written as:

        foreach (String str in years)
        {
            if (string.IsNullOrEmpty(str))
                System.Diagnostics.Debug.WriteLine("empty");
            else
            {
                yearList.Add(str);
            }
        }

Then you are not having to worry about the count and 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 add using 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.

Colin Mackay
  • 18,736
  • 7
  • 61
  • 88
  • My question is i am getting index out of bounds exception. I dont know why so you are correct.. And yeah..How do I declare a dynamic array here?? please suggest – Naga Oct 25 '12 at 22:44
  • Thanks Colin, it solved my issue...but one correction, we cannot add string to List of List items..I figured out anyway – Naga Oct 25 '12 at 22:57
0

why use Foreach loop when you can just use For if you want to keep counter?

        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);
            }
        }
Mayank
  • 8,777
  • 4
  • 35
  • 60
  • I did use this one too..but the same problem..so I shifted to foreach..but that dint help..so.. – Naga Oct 25 '12 at 22:42
  • well @ColinMackay explained you the problem and gave you the answer, but I was just saying it's not good that you are not using the provided tools. – Mayank Oct 25 '12 at 22:44
  • I understand now that you tried `for` loop before and than switched to `foreach` just because there was `IndexOutOfBoundsException`. – Mayank Oct 25 '12 at 23:13
0

I don't know what your objective is, and I don't have any experience with ListItem, but have you considered this approach:

string[] yearList = years.Where(y => !string.IsNullOrEmpty(y)).ToArray();

This creates an array of all the years that are not null or empty. It also depends how you are consuming the list as to whether this is useful. If it doesn't need to be an array, then you could even do this instead:

var yearList = years.Where(y => !string.IsNullOrEmpty(y));

Note that these solutions don't do exactly what your code does in terms of diagnostic output or the use of ListItem. It also depends what version of .net you are using as to whether this is an option for you.

Mike
  • 954
  • 6
  • 10