'Display information in datagridview

I created a database first model from my database and wrote the following code in the form load event:

This error is displayed when the form is opened:

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index '

Code:

using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace Automation
    {
        public partial class Kanoon : Form
        {
            public Kanoon()
            {
                InitializeComponent();
            }
    
            private void Kanoon_Load(object sender, EventArgs e)
            {
                BindGrid();
            }
            private void BindGrid()
            {
    
                using (KanoonEntities db = new KanoonEntities())
                {
                    gdPersons.AutoGenerateColumns = false;
                    gdPersons.DataSource = db.Persons.ToList();
                }
    
            }
    
        }
    }


Solution 1:[1]

You can use the BindingComplete event, which fires when all the databinding for the Gridview is finished, so you could access properties that are correctly binded at that time. You need to set the attribute in your Initiallize and put the code in yours:

BindingSource bindingSource1 = new BindingSource();

bindingSource1.BindingComplete +=
   new BindingCompleteEventHandler(bindingSource1_BindingComplete);
using (KanoonEntities db = new KanoonEntities())
{
    // Set the data source to the DataSet.
    bindingSource1.DataSource = db.Persons.ToList();

   // Add the control data bindings.
   gdPersons.DataSource = bindingSource1;

}

Then use the event:

private void bindingSource1_BindingComplete(EventArgs e)
{
    ...
}

I tried to keep this generic, as is a bit unclear what are you trying to achieve with that visible = true;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1