Anon Anon - 3 months ago 57
C# Question

DataGridView is editable but does not send changes back to database using Entity Framework

I've bound my

DataGridView
to my
ComboBox
so that whatever value is selected in the
ComboBox
, the corresponding valued for SID and Mark will appear in the
DataGridView
. The
DataGridView
is editable when I do this but the data is not saved in the database when it is input. Is there a way to update it? If there's another method, I have to first warn that I only need SID and Mark in the
DataGridView
, if I try to bind the whole "Student_Course" table to the
DataGridView
I get other columns I don't need.

private void cboeCID_SelectedIndexChanged_1(object sender, EventArgs e)
{
var CID = Convert.ToInt32(cboeCID.Text);
using (var db = new Entities2())
{
var course = from c in db.Student_Course
where c.CID == CID
select new Class1
{
SID = c.SID,
Mark = c.Mark
};
editDataGridView.DataSource = course.ToList();
Validate();
editDataGridView.EndEdit();
editDataGridView.Update();
}
}

class Class1
{
public int SID { get; set; }
public int Mark { get; set; }

}

Answer

There are some important issues in above code:

  1. You shaped the result of query to a custom Class1 which is not your entity type.

  2. You used a DbContext in using statement which means db is disposed after the using statement and will not track changes.

  3. You called SaveChanges on another instance of your DbContext which is not aware of changes, so nothing happens.

To solve above issues consider these tips:

  1. Create db as a field of Form and instantiate it in Load event of Form and use it for both loading and saving data.
  2. You can load data entity this way:

    db = new Entities2();
    db.Student_Course.Where(x => c.CID== CID).ToList();
    editDataGridView.DataSource = db.Student_Course.Local; 
    
  3. You can save data this way:

    editDataGridView.EndEdit();
    db.SaveChanges();
    
  4. If you need to use a view model different than your entity for edit, when saving changes you should first load original entities from database using another instance of your context, then for each entity set the value of changed field and then call SaveChanges method.

For more information take a look at these resources: