Search code examples
winformslinq-to-sqldatagridviewbindingsource

DataGridView CRUD Operation with LINQ to SQL


I have a datagridview with BindingSource to Linq to SQL as datasource. When I try to insert or delete the data, the gridview is not refreshed.

SampleDataContext context = new SampleDataContext();
    BindingSource bindingSource = new BindingSource();

    public Form1()
    {
        InitializeComponent();

        bindingSource.DataSource = context.Persons;
        PersonGridView.DataSource = bindingSource;
    }

    private void AddButton_Click(object sender, EventArgs e)
    {
        context.Persons.InsertOnSubmit(new Person { Name = , Address =  });
        context.SubmitChanges();
    }

    private void DeleteButton_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in PersonGridView.SelectedRows)
        {
            var person = context.Persons.FirstOrDefault(x => x.ID == int.Parse(row.Cells[0].Value.ToString()));
            context.Persons.DeleteOnSubmit(person);
        }

        context.SubmitChanges();
    }   

Am I missing something here ?

Best Regards,

Brian


Solution

  • Viola after try many solutions I Have a better solution just change insert and delete operation to bindingsource

    SampleDataContext context = new SampleDataContext();
        BindingSource bindingSource = new BindingSource();
    
        public Form1()
        {
            InitializeComponent();
    
            bindingSource.DataSource = context.Persons;
            PersonGridView.DataSource = bindingSource;
        }
    
        private void AddButton_Click(object sender, EventArgs e)
        {
            bindingSource.Add(new Person { Name = "Hello", Address = "Hahahaha123" });
            context.SubmitChanges();
        }
    
        private void DeleteButton_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in PersonGridView.SelectedRows)
            {
                var person = context.Persons.FirstOrDefault(x => x.ID == int.Parse(row.Cells[0].Value.ToString()));
                bindingSource.Remove(person);
            }
    
            context.SubmitChanges();
        }