2013-04-11 70 views
1

我有一个使用BindingSource将Linq to SQL作为数据源的datagridview。当我尝试插入或删除数据时,gridview不刷新。DataGridView CRUD使用LINQ to SQL操作

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

我在这里错过了什么吗?

最好的问候,

布赖恩

回答

1

中提琴后尝试了很多解决方案,我有一个更好的解决办法只是改变插入和删除操作的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(); 
    }