如何使用Linq to Entity在BidingNavigator上单击Save buton后插入在GridView中添加的数据。
我正在尝试向数据库添加数据,但是会出现一些问题。我正在使用此代码显示数据:
...
private void PostojeciPRojekti_Load(object sender, EventArgs e)
{
dbcontext = new logicrms2Entities1();
var projekti = from c in dbcontext.projekti
select c;
projektiBindingSource.DataSource = projekti.ToList();
projektiGridControl.Refresh();
}
...
修改
我尝试使用以下方法保存数据:
private void projektiBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
dbcontext.SaveChanges();
gridView1.RefreshData();
}
答案 0 :(得分:1)
首先在表单中维护一个新添加的对象列表:
private List<projekti> addedList = new List<projekti>();
然后,在DataGridView上处理 RowsAdded 事件:
dataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(dataGridView1_RowsAdded);
接下来,将任何添加的对象添加到RowsAdded事件处理程序的列表中:
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
addedList.Add(dataGridView1.Rows[e.RowIndex].DataBoundItem as projekti);
}
最后,在导航器的保存按钮单击事件处理程序方法中,您可以存储对象:
private void saveButton_Click(object sender, EventArgs e)
{
var dbcontext = new logicrms2Entities1();
addedList.ForEach(p=> dbcontext.projeckit.Add(p));
dbcontext.SaveChanges()
}