-4

Why is there IndexOutOfRange exception being thrown? The index is set to iterate through 0 to the List.Count... I'll post my code below.

public void ShowButtons()
{
    Appliances = data.GetAppliances();

    for (int x = 0; x <= Appliances.Count; x++)
    {
        appButtons[x] = new Button();
        appButtons[x].Size = new System.Drawing.Size(75, 25);
        appButtons[x].Text = Appliances[x].Name;
        ButtonBoard.Controls.Add(appButtons[x]);
    }
}
Andronicus
  • 25,419
  • 17
  • 47
  • 88
  • 4
    The problem is `x <= Appliances.Count`. Since it is indexed from zero, you need to use `x < Appliances.Count`; no equality. This is out of range. And the Out of range exception can also be caused by `appButtons[x]`. How many buttons do you have in the `appButtons` array? – Julo Jan 29 '19 at 05:16

2 Answers2

2

Loop should go upto Appliances.Count-1 or it can be like @Julo said

The problem is x <= Appliances.Count. Since it is indexed from zero, you need to use x < Appliances.Count; no equality. This is out of range.

Your code should be

for (int x = 0; x < Appliances.Count; x++)
            {
                appButtons[x] = new Button();
                appButtons[x].Size = new System.Drawing.Size(75, 25);
                appButtons[x].Text = Appliances[x].Name;
                ButtonBoard.Controls.Add(appButtons[x]);
            }

or it can be

for (int x = 0; x <= Appliances.Count-1; x++)
            {
                appButtons[x] = new Button();
                appButtons[x].Size = new System.Drawing.Size(75, 25);
                appButtons[x].Text = Appliances[x].Name;
                ButtonBoard.Controls.Add(appButtons[x]);
            }
ahmednawazbutt
  • 823
  • 12
  • 34
0

Count returns number of elements in an array. If your array is of length 5, i.e

int[] array = {10, 20, 30, 40, 50};

Array index starts from 0 to n, in your case 0 to 4.

When you iterate array you need to iterate from 0 to n - 1 as indexing starts from 0. Instead of doing for loop upto Application.Count, iterate upto Application.Count - 1

for (int x = 0; x <= Appliances.Count-1; x++)
            {
                appButtons[x] = new Button();
                appButtons[x].Size = new System.Drawing.Size(75, 25);
                appButtons[x].Text = Appliances[x].Name;
                ButtonBoard.Controls.Add(appButtons[x]);
            }
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44