Winforms 使用LINQ到SQL的DataGridView CRUD操作
我有一个datagridview,其中BindingSource到Linq到SQL作为数据源。当我尝试插入或删除数据时,gridview不会刷新Winforms 使用LINQ到SQL的DataGridView CRUD操作,winforms,linq-to-sql,datagridview,bindingsource,Winforms,Linq To Sql,Datagridview,Bindingsource,我有一个datagridview,其中BindingSource到Linq到SQL作为数据源。当我尝试插入或删除数据时,gridview不会刷新 SampleDataContext context = new SampleDataContext(); BindingSource bindingSource = new BindingSource(); public Form1() { InitializeComponent(); bin
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();
}
我是不是遗漏了什么
致以最良好的祝愿
BrianViola在尝试了许多解决方案后,我有了一个更好的解决方案,只需将insert和delete操作更改为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();
}
Viola在尝试了许多解决方案后,我有了一个更好的解决方案,只需将insert和delete操作更改为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();
}