friends. I really need your help. I would be very grateful.
And so I have the entity "Model" c field "ID_model" and "name" in MS SQL Server. I want, after clicking "Edit" on Form1, there is another form (FormModel) where you can change the data and write changes to the database.
The problem is that after pressing "Edit" there is an error about "Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker" And I don't know how to fix it.
Code from Form1:
public partial class Form1 : Form
{
MyDBEntities db2;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
db2 = new MyDBEntities();
modelBindingSource.DataSource = db2.Models.ToList();
dataGridView.Columns.RemoveAt(2);
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (modelBindingSource.Current == null)
return;
using (FormModel frm = new FormModel(modelBindingSource.Current as Model))
{
if (frm.ShowDialog() == DialogResult.OK)
{
modelBindingSource.DataSource = db2.Models.ToList();
}
}
}
}
Code from FormModel:
public partial class FormModel : Form
{
MyDBEntities db2;
public FormModel(Model obj)
{
InitializeComponent();
db2 = new MyDBEntities();
if (obj == null)
{
modelBindingSource.DataSource = new Model();
db2.Models.Add(modelBindingSource.Current as Model);
}
else
{
modelBindingSource.DataSource = obj;
db2.Models.Attach(modelBindingSource.Current as Model);
}
}
private void FormModel_FormClosing(object sender, FormClosingEventArgs e)
{
if (DialogResult == DialogResult.OK)
{
if (string.IsNullOrEmpty(txtModelName.Text))
{
MessageBox.Show("There are empty fields", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtModelName.Focus();
e.Cancel = true;
return;
}
db2.SaveChanges();
e.Cancel = false;
}
e.Cancel = false;
}
}
I really hope help. All the best. And excuse me for my English.