Hello,
I have literally spent the last week struggling with that.. I've read and tested probably all examples on the Internet and I still can't get it to work well.
I have a WinForms application that connects to a MSSQL database and manipulates with the data.
I have a sample form where I have a grid view and four buttons: add, save, cancel and delete.
When the form loads I initialize my DbContext(I am using Entity Framework 4.0) and I get a List<Books> and assign it to a BindingSource that I have as a DataSource of the DataGridView:
var booksList = context.Books.ToList();
bindingSource1.DataSource = null;
bindingSource1.DataSource = booksList;
Until here everything works great. Now my problems start when I try to manipulate with the data.
How can I add and edit the data?
Should I add it to the
BindingSource
, or to the
List<Books>
, or to the
DataGridView
?
To save the data, I have this code:
private void saveBtn_Click(object sender, EventArgs e)
{
bindingSource1.EndEdit();
context.Save();
}
And to add, I've tried quite a few:
private void addBtn_Click(object sender, EventArgs e)
{
var newRow = context.Books.Create();
newRow.Context = context.getContext();
}
I've also tried that:
private void addBtn_Click(object sender, EventArgs e)
{
gridView1.AddNewRow();
}
I have also added some validation that will prompt the user that a certain cell is not filled properly. It works fine.
Editing the existing rows and saving works fine.