C# Entity Framework and refreshing listBox after insert

可紊 提交于 2019-12-12 05:03:18

问题


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.



来源:https://stackoverflow.com/questions/2763807/c-sharp-entity-framework-and-refreshing-listbox-after-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!