插入后,C#实体框架和刷新列表框 [英] C# Entity Framework and refreshing listBox after insert
问题描述
我有这个代码的问题:
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?
对不起,我的英文和一些捷克语的代码。 (字典:Knihovny - >书架,Nazev - >名称)
Sorry for my english and some Czech words in code. (Dictionary: Knihovny -> Bookcase, Nazev -> Name)
推荐答案
You need to add a DataBinding. Have a look at this or this.
初始化时设置DataSource将获取当前值,但动态更新需要绑定。
Setting the DataSource on initialization gets the current value, but dynamic updates require a binding.
这篇关于插入后,C#实体框架和刷新列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!