2013-04-11 67 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(); 
    }