/ / DataGridView CRUD Operação com LINQ to SQL - winforms, linq-to-sql, datagridview, bindingsource

Operação CRUD do DataGridView com LINQ para SQL - winforms, linq-para-sql, datagridview, bindingsource

Eu tenho um datagridview com BindingSource para Linq to SQL como fonte de dados. Quando tento inserir ou excluir os dados, o gridview não é atualizado.

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

Estou faltando alguma coisa aqui?

Cumprimentos,

Brian

Respostas:

1 para resposta № 1

Viola depois de tentar muitas soluções Eu tenho uma solução melhor, basta alterar a operação de inserção e exclusão para 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();
}