I have a simple project with Entity Framework, I have a DataGridView
in my Form
and I set its AllowUserToAddRow
property to true
but still I can not add new rows into it.
And here is my code:
DBEntities context = new DBEntities();
private void Form1_Load(object sender, EventArgs e)
{
var q = (from i in context.myTable
select i).ToList();
DataGridView.DataSource = q;
}
private void btnSave_Click(object sender, EventArgs e)
{
context.SaveChanges();
MessageBox.Show("saved successfully");
}
If I use a BindingSource
control, it allow me to insert rows in DataGridView
but with this approach after I call context.SaveChanges()
nothing insert in my database file. So I thought maybe its relative to this problem that DataGridView
with true
AllowUserToAddRow
property doesn't let me to insert row in DataGridView
.
ToList()
method. I removedToList()
method and now it works fine with both insertion or delete. But still it throw an exception in insertion if you have auto-increment (pk) column in yourDataGridView
. Do you have any suggestion how to handle that exception? – Dactyl