When running through a loop, my loop processes through the first iteration without errors, then fails with an Index out of Bounds error. Walking through the code, I'm not able to see why it's throwing this exception.
I also changed the loop iterations to i < 1
, which allowed the program to run. When I changed the iterations to i < 2
, I received the exception error again.
The code I have does this:
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);
}
}
From what is programmed, I would expect the loop to run through 7 iterations, then load the information to the DataGridView when I run the program.