Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C#
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:
C#
private void saveBtn_Click(object sender, EventArgs e)
{
    bindingSource1.EndEdit();
    context.Save();
}


And to add, I've tried quite a few:

C#
private void addBtn_Click(object sender, EventArgs e)
{
    var newRow = context.Books.Create();
    newRow.Context = context.getContext();
// with the hope that creating the record in the context will also add it to the BindingSource, which will add a new row in the grid
}


I've also tried that:
C#
private void addBtn_Click(object sender, EventArgs e)
{
    gridView1.AddNewRow();
// with the hope that the added row in the grid will be also added to the BindingSource and to the context
//I don't get any errors but the data isn't saved in the database
}


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.
Posted
Updated 9-Nov-14 10:52am
v2
Comments
NaveenReddy2458 10-Nov-14 1:52am    
try using dataset and datarow instead of databinding

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900