在循环中运行时,我的循环在进行第一次迭代时不会出错,然后因Index of Bounds出错而失败。遍历代码,我看不到为什么会引发此异常。
我还将循环迭代更改为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 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。
答案 0 :(得分:0)
Chris Dunaway和Srikanth是正确的:我没有添加任何行,因为那时候我一直盯着代码看了几个小时,并且只是没有思考。感谢您的帮助!