我试图让列表显示在我的组合框中,每当用户输入新的船名和船牌时,他们都会被添加到组合框中。
我已经尝试过使用for循环来完成此操作,但这给了我一个我理解如何修复它的bug。
for(int i = 0; i < boatList.Count; i++)
{
BoatSelector.Items.Add(boatList[i].GetboatName() + " - " + boatList[i].GetboatLicense());
}
预期结果:用户输入的名称+许可证,应添加到组合框中。
实际结果:添加名称+许可证,然后for循环,循环回到0,并重新添加相同的名称和许可证,同时还添加任何更新的名称和许可证。
我希望存储而不是清除项目,我将如何在新索引上开始循环?
您的意思是在列表的开头吗?如果是这样,您可以使用InsertAt
BoatSelector.Items.InsertAt(0,boatList[i].GetboatName() + " - " + boatList[i].GetboatLicense());
我认为您要多次添加项目。
for(int i = 0; i < boatList.Count; i++)
{
BoatSelector.Items.Add(boatList[i].GetboatName() + " - " + boatList[i].GetboatLicense());
}
(... at another time)
for(int i = 0; i < boatList.Count; i++)
{
BoatSelector.Items.Add(boatList[i].GetboatName() + " - " + boatList[i].GetboatLicense());
}
这意味着BoatSelector.Items
总是增长。
您可以Clear()
Items
或分配新列表:
BoatSelector.Items = boatList
.Select( item => item.GetboatName() + " - " + item.GetboatLicense())
.ToList();