第二次迭代开始时出现索引越界错误

Index out of Bounds error at beginning of second iteration

当运行通过一个循环时,我的循环在第一次迭代中没有错误地处理,然后失败并出现索引越界错误。浏览代码,我不明白为什么会抛出这个异常。

我还将循环迭代更改为 i < 1,这允许程序 运行。当我将迭代更改为 i < 2 时,我再次收到异常错误。

我的代码是这样做的:

    private void build()
    {
      AllPartsList.PartsList.Clear();
      AllPartsList.PartsList.Add(new InHouse(1, "Part 1", 5.0, 5, 15, 3, 25));
      AllPartsList.PartsList.Add(new InHouse(2, "Part 2", 10.0, 10, 25, 5, 2));
      AllPartsList.PartsList.Add(new Outsourced(3, "Part 3", 15.0, 12, 20, 7, "Acme"));
      AllPartsList.PartsList.Add(new Outsourced(4, "Wheel", 12.0, 15, 30, 10, "Carpathia"));
      AllPartsList.PartsList.Add(new Outsourced(5, "Pedal", 8.0, 24, 50, 22, "BendORama"));
      AllPartsList.PartsList.Add(new Outsourced(6, "Chain", 9.0, 12, 15, 3, "Michael's Metals"));
      AllPartsList.PartsList.Add(new InHouse(7, "Seat", 4.0, 8, 10, 2, 15));
    }

    private void display()
    {
      PartTable.Rows.Clear();
      PartTable.Refresh();
      for (int i = 0; i < AllPartsList.PartsList.Count; i++)
      {
        PartTable.Rows[i].Cells[0].Value = AllPartsList.PartsList[i].PartID;
        PartTable.Rows[i].Cells[1].Value = AllPartsList.PartsList[i].PartName;
        PartTable.Rows[i].Cells[2].Value = AllPartsList.PartsList[i].price;
        PartTable.Rows[i].Cells[3].Value = AllPartsList.PartsList[i].inStock;
      }
    }

AllPartsList class:

    class AllPartsList
    {
      private static BindingList<Part> partsList = new BindingList<Part>();
      public static BindingList<Part> PartsList { get { return partsList; } set { partsList = value; } }

      public static string CurrentPart { get; set; }
      public static int CurrentPartID { get; set; }
      public static int CurrentPartIndex { get; set; }
      public static double CurrentPartPrice { get; set; }
      public static int CurrentPartInventory { get; set; }

      public static Part lookupPart(int i)
      {
        for (int j = 0; j < PartsList.Count; j++)
        {
          if (PartsList[j].PartID.Equals(i))
          {
            CurrentPartIndex = j;
            return PartsList[j];
          }
        }
        CurrentPartIndex = -1;
        return null;
      }

      internal static void swap(Part prt)
      {
        PartsList.Insert(CurrentPartIndex, prt);
        PartsList.RemoveAt(CurrentPartIndex + 1);
      }
    }  

根据编程的内容,我希望通过 7 次迭代循环到 运行,然后在我 运行 程序时将信息加载到 DataGridView。

Chris Dunaway 和 Srikanth 是正确的:我没有添加任何行,因为那时我已经盯着代码看了好几个小时,只是没有思考。感谢您的帮助!