我的厨房列表格式为List<Tuple<string,string,string>>
。我可以在厨房类方法中填充它,并且可以通过在我对它应用foreach循环时通过厨房类对象调用该方法来在datagridview上显示它,以显示索引范围异常
kitchen = new Kitchen();
List<Tuple<string, string, string>> kitchenList = kitchen.getKitchens();
dgv_kitchen.Rows.Clear();
if (kitchenList.Count > 0)
{
for (int i = 0; i < kitchenList.Count; i++)
{
dgv_kitchen.Rows[i].Cells["id"].Value = kitchenList[i].Item1.ToString();
dgv_kitchen.Rows[i].Cells["kitchen_name"].Value = kitchenList[i].Item2.ToString();
dgv_kitchen.Rows[i].Cells["categories"].Value = kitchenList[i].Item3.ToString();
}
}
答案 0 :(得分:4)
您正在清除行列表-但随后尝试按索引访问那些不存在的行。与您的标题相反,并不是导致问题的“遍历元组列表”,而是您对结果的处理方式。
相反,您应该创建新行并添加。请注意,使用foreach
循环比使用for
循环更容易,而且您无需先检查计数的任何一种方式:
kitchen = new Kitchen();
List<Tuple<string, string, string>> kitchenList = kitchen.getKitchens();
dgv_kitchen.Rows.Clear();
foreach (var tuple in kitchenList)
{
dgv_kitchen.Rows.Add(new object[] { tuple.Item1, tuple.Item2, tuple.Item3 };
}
假设DataGridView
仅按此顺序显示id
/ kitchen_name
/ categories
。
更好的解决方案是避免直接设置单元格值,而是将DataGridView
绑定到数据源。我也要避免元组。所以你可能有:
public class Kitchen
{
public string Id { get; }
public string Name { get; }
public string Categories { get; }
public Kitchen(string id, string name, string categories)
{
Id = id;
Name = name;
Categories categories;
}
}
然后,您将当前的getKitchens
方法更改为:
public IReadOnlyList<Kitchen> GetKitchens()
然后,您可以将所有现有代码替换为:
dgv_kitchens.DataSource = GetKitchens();