-1

enter image description here

my kitchen list format are this List<Tuple<string,string,string>> .I can filled it on kitchen class method and i can display it on datagridview by calling that method by kitchen class object when i apply foreach loop on it it show me index out of range exception

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();
    }
}

enter image description here

  • 2
    Possible duplicate of [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Camilo Terevinto Jul 12 '18 at 12:27
  • my case is totally different from previous answer i find alot but nothing any link or previous answer solved my problem – Syed Nazir Hussain Jul 12 '18 at 12:32

1 Answers1

4

You're clearing the list of rows - but then trying to access those non-existent rows by index. Contrary to your title, it's not "looping through a tuple list" that's causing the problem - it's what you're doing with the results.

Instead, you should be creating new rows and adding them. Note that this is easier with a foreach loop than a for loop, and you don't need to check the count first either way:

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 };
}

That's assuming the DataGridView displays just id/kitchen_name/categories in that order.

A better solution would be to avoid setting the cell values directly, and instead bind the DataGridView to a data source. I'd also avoid the tuples. So you might have:

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;
    }
}

You'd then change your current getKitchens method to something like:

public IReadOnlyList<Kitchen> GetKitchens()

Then you can replace all of the existing code with:

dgv_kitchens.DataSource = GetKitchens();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194