Hi everyone.
Ok, this has been driving me nuts for the last two days!
I'm new to C# aand have been teaching myself via writing a simple app.
I have a simple form that comprises of a combobox and two text boxes. The combobox contains a list of the entities in the database table. The text boxes allow the user to add new entries. It is simply a list of names (first and surname).
On the form are three buttons to Add, Modify and Delete.
Behind the scenes I'm using databinding and WPF.
Ok my problem is this..
For both the delete and the modify operation everything works as I would expect. The database is changed accordingly and (importantly) the combobox INSTANTLY reflects the changes made to the databound entity.
BUT when I create and add a new entity the database is updated correclty with the new item BUT the combobox does NOT show the new entity (name) in its list. You have to exit the form and come back in in order to see the combobox correctly reflect the database table with the newly added item.
Can someone tell me what the correct practise is for getting a databound control to reflect an INSERT change on the table it is bound to?
relevant code snippets below...
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.myContext = new myEntities();
// bind the contents of the table to the combobox
myComboBox.DataContext = myContext.myPeople;
}
private void myComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Update the text boxes to reflect the currently selected name
this.person = myComboBox.SelectedItem as myPerson;
if (this.person != null)
{
tbFirstName.Text = this.person.Firstname;
tbSurname.Text = this.person.Surname;
}
}
//User actions...
if (userAction == crudAction.Modify)
{
// Update via the Entity Framework
person.Firstname = tbFirstName.Text;
person.Surname = tbSurname.Text;
msg = "Person details modified";
}
if (userAction == crudAction.Add)
{
person = new myPerson();
person.Firstname = tbFirstName.Text;
person.Surname = tbSurname.Text;
person.idPeople = 0; //Autoincremented db key
myContext.myPeople.AddObject(person);
msg = "New person added";
}
if (userAction == crudAction.Delete)
{
myContext.myPeople.DeleteObject(person);
msg = "Person deleted";
}
myContext.SaveChanges();