Entity framework 绑定到Datagridview的添加删除修改

时间:2022-09-02 17:20:05

Entity framework 绑定到Datagridview的添加删除修改

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace EFBindingDataGridView
{
public partial class Form1 : Form
{
Model1 model = new Model1();
List<Setting> list = new List<Setting>();
public Form1()
{
InitializeComponent();
} private void loadButton_Click(object sender, EventArgs e)
{
list = model.Settings.ToList() ;
bindingSource1.DataSource = list;
dataGridView1.DataSource = bindingSource1;
} private void saveButton_Click(object sender, EventArgs e)
{
dataGridView1.EndEdit();
bindingSource1.EndEdit();
//保存前把新增的对象加入
foreach(Setting item in list)
{
if(model.Entry(item).State == System.Data.Entity.EntityState.Detached)
{
model.Settings.Add(item);
}
}
model.SaveChanges();
} private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
//获取删除的对象
Setting set = (Setting)e.Row.DataBoundItem;
model.Settings.Remove(set);
} }
}