C# Entity Framework and refreshing listBox after i

2019-09-14 22:32发布

问题:

i have a problem with this code:

public partial class KnihovnyForm : Form
{
    DatabazeEntities db;

    public KnihovnyForm()
    {
        InitializeComponent();

        db = new DatabazeEntities();

        knihovnyListBox.DataSource = db.Knihovny;
        knihovnyListBox.DisplayMember = "Nazev";
    }

    protected override void OnFormClosed(FormClosedEventArgs e)
    {
        base.OnFormClosed(e);
        db.Dispose();
    }


    private void novaButton_Click(object sender, EventArgs e)
    {
        string text = "";
        if (InputForm.ShowDialog("Název nové knihovny", ref text) == DialogResult.OK)
        {
            Knihovna n = new Knihovna() { Nazev = text };
            db.AddToKnihovny(n);
            db.SaveChanges();

            CurrencyManager cm = (CurrencyManager)BindingContext[db.Knihovny];
            cm.Refresh();
        }
    }
}

When I add new item to database, i want to show it in the listBox. But it looks like the Entity Framework don't update context or something like that. If i close this form and open it again all items (including the new one) are show correctly. How can I show all items immediately after insert?

Sorry for my english and some Czech words in code. (Dictionary: Knihovny -> Bookcase, Nazev -> Name)

回答1:

You need to add a DataBinding. Have a look at this or this.

Setting the DataSource on initialization gets the current value, but dynamic updates require a binding.