2013-04-11 5 views
1

У меня есть datagridview с BindingSource для Linq to SQL в качестве источника данных. Когда я пытаюсь вставить или удалить данные, 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(); 
    } 

Я что-то упустил?

С наилучшими пожеланиями,

Brian

ответ

1

Viola после попробовать множество решений У меня есть лучшее решение, просто изменить вставку и операцию в 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(); 
    } 
Смежные вопросы