1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 10 namespace EFBindingDataGridView 11 { 12 public partial class Form1 : Form 13 { 14 Model1 model = new Model1(); 15 List<Setting> list = new List<Setting>(); 16 public Form1() 17 { 18 InitializeComponent(); 19 } 20 21 private void loadButton_Click(object sender, EventArgs e) 22 { 23 list = model.Settings.ToList() ; 24 bindingSource1.DataSource = list; 25 dataGridView1.DataSource = bindingSource1; 26 } 27 28 private void saveButton_Click(object sender, EventArgs e) 29 { 30 dataGridView1.EndEdit(); 31 bindingSource1.EndEdit(); 32 //保存前把新增的对象加入 33 foreach(Setting item in list) 34 { 35 if(model.Entry(item).State == System.Data.Entity.EntityState.Detached) 36 { 37 model.Settings.Add(item); 38 } 39 } 40 model.SaveChanges(); 41 } 42 43 44 private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e) 45 { 46 //获取删除的对象 47 Setting set = (Setting)e.Row.DataBoundItem; 48 model.Settings.Remove(set); 49 } 50 51 } 52 }
时间: 2024-10-10 09:58:50