将 ADO.NET 实体框架数据绑定到列表框
我正在尝试将 ADO EF 对象类(材质)附加到 ListBox,并在将新材质添加到数据库时自动更新。
在下面我当前的代码中,它将显示设置控件数据源之前数据库中的任何项目,但它不会更新。
我知道我在这里遗漏了一些基本的东西。非常感谢任何帮助!
public partial class Main : KryptonForm
{
private AGAEntities db = new AGAEntities();
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
matList.DataSource = db.Materials;
matList.DisplayMember = "Name";
}
private void newMat_Click(object sender, EventArgs e)
{
AddMaterial form = new AddMaterial();
form.ShowDialog();
}
}
I'm trying to attach a ADO EF object class (Materials) to a ListBox, and have it auto-update when a new material is added to the database.
In my current code below, it will show any items that are in the database before the controls datasource is set, but it will not update.
I know I'm missing something elementary here. Any help is greatly appreciated!
public partial class Main : KryptonForm
{
private AGAEntities db = new AGAEntities();
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
matList.DataSource = db.Materials;
matList.DisplayMember = "Name";
}
private void newMat_Click(object sender, EventArgs e)
{
AddMaterial form = new AddMaterial();
form.ShowDialog();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为
db.Materials
在添加项目时不会发出通知。您应该使用BindingList
作为DataSource
:(此代码假定您的
AddMaterial
类将新项目添加到数据库并公开它通过NewMaterial
属性)That's because
db.Materials
doesn't raise a notification when an item is added to it. You should use aBindingList<T>
as theDataSource
:(This code assumes that your
AddMaterial
class adds the new item to the DB and exposes it through aNewMaterial
property)