Search code examples
c#datagridviewimap

c# > Index was out of range. Must be non-negative and less than the size of the collection


I get the index out of range exception when compiling my grid view to display a set of orders.

It doesn't return all rows . it's return one row only

Any help is much appreciated.

 try
                {
                    oClient.Connect(oServer);
                    MailInfo[] infos = oClient.GetMailInfos();
                    Console.WriteLine(infos.Length);
                    for (int i = 0; i < infos.Length; i++)
                    {
                        MailInfo info = infos[i];
                        Mail oMail = oClient.GetMail(info);

                        dgView_Inbox.Rows[i].Cells[0].Value = oMail.From.ToString();
                        dgView_Inbox.Rows[i].Cells[1].Value = oMail.Subject.ToString();

                    }
                    oClient.Quit();


                }
                catch (Exception ep)
                {
                    Console.WriteLine(ep.Message);
                }

Solution

  • Insert an Add command in your loop and use its index:

    int newrow = dgView.Rows.Add();
    dgView_Inbox.Rows[newrow ].Cells[0].Value = oMail.From.ToString();
    dgView_Inbox.Rows[newrow ].Cells[1].Value = oMail.Subject.ToString();