I have this form with a DataGrid in it+an edit button and by using edit button another window opens and selected item in DataGrid will be passed to edit window using an argument in it's constructor. so user edits items and when user clicks on save the data saves.
it has no problem with normal fields and works perfectly fine.the problem is about combo Box fields. if u edit a referenced field when u want to save changes it throws an exception.
Exception is:
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
Here is the code I use:
Main Window With DataGrid:
privatevoid cmdEdit_Click(object sender,RoutedEventArgs e){ConsignDialog _dlg =newConsignDialog(lstConsign.SelectedItemasConsigner,true);
_dlg.ShowDialog();if(_dlg.DialogResult.HasValue&& _dlg.DialogResult.Value)
_db.SaveChanges();RefreshList();}
Save Button Code In Edit Window:
privatevoid cmdSave_Click(object sender,RoutedEventArgs e){DialogResult=true;if(!IsEditing){
_db.Consigners.Add(consigner);}this.Close();}
Constructor of Edit Window:
publicpartialclassConsignDialog:Window{publicConsigner consigner { get;set;}DBEntities _db =newDBEntities();
bool IsEditing=false;publicConsignDialog(Consigner con,bool EditMode){IsEditing=EditMode;
consigner = con;this.DataContext=this.consigner;InitializeComponent();
cmbUsage.ItemsSource= _db.EstateUsages.ToList();}}
Definition of cmbUsage which if you change it you can't call SaveChanges
anymore:
<ComboBox x:Name="cmbUsage"ItemsSource="{Binding}"SelectedItem="{Binding DataContext.EstateUsage, ElementName=wndConsign}"DisplayMemberPath="Name"SelectedValuePath="ID"Margin="37,0,0,0"Grid.Column="2"/>