简体   繁体   中英

C# Entity Framework - Data bound combobox does not reflect changes made after .SaveChanges()

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();

Does it get updated if you requery the DB after running SaveChanges() ?

var test = myContext.myPeople.ToList();

Edit:

Set the ItemsSource for the ComboBox again instead:

myComboBox.ItemsSource = context.myPeople.ToList();

You can use events to update the Combobox SourceItems on a parent page that displays

ie in your custom control or form that handles creating the new item

    public static readonly RoutedEvent NewItemAddedEvent =
        EventManager.RegisterRoutedEvent("NewItemAdded", RoutingStrategy.Bubble,
            typeof(RoutedEventHandler), typeof(CloseableTabItem));

    public event RoutedEventHandler NewItemAdded
    {
        add { AddHandler(NewItemAddedEvent, value); }
        remove { RemoveHandler(NewItemAddedEvent, value); }
    }

private void SaveButton_Click(object sender, RoutedEventArgs e) { ProActive.Contact currentContact = (ProActive.Contact)ItemsListBox.Items.CurrentItem;

        switch (MessageBox.Show("Are you sure?", "Save Changes", MessageBoxButton.YesNoCancel))
        {
            case MessageBoxResult.Yes:
                if (currentContact.EntityState == System.Data.EntityState.Detached)
                    ProActive.App.ProActiveDatabaseEntities.Contacts.AddObject(currentContact);
                ProActive.App.ProActiveDatabaseEntities.SaveChanges();

                this.RaiseEvent(new RoutedEventArgs(NewItemAddedEvent, this));

                break;
}

then in the master page that displays the combo box, attach the event that fired after you 'save' the new item

ProActive.TabPagesControls.AllContactsDetailsControl cdc = new AllContactsDetailsControl();
cdc.NewItemAdded += AllContactsDetailsNewItemAdded;

then handle the event on the parent page after it gets fired to re-load the itemssource

  private void AllContactsDetailsNewItemAdded(object sender, RoutedEventArgs e)
    {
        // New item added so refresh the items listbox
        AllContactListItemsListBox.ItemsSource = from c in  ProoActive.App.ProActiveDatabaseEntities.Contacts select c;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM