简体   繁体   English

将ADO.NET实体框架绑定到ListBox

[英]Databind ADO.NET Entity Framework to ListBox

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. 我正在尝试将ADO EF对象类(材料)附加到ListBox,并在将新材料添加到数据库时使其自动更新。

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

That's because db.Materials doesn't raise a notification when an item is added to it. 这是因为db.Materials在添加项目时不会引发通知。 You should use a BindingList<T> as the DataSource : 您应该使用BindingList<T>作为DataSource

private BindingList<Material> _materials;

private void Main_Load(object sender, EventArgs e)
{
    _materials = new BindingList<Material>(db.Materials);
    matList.DataSource = _materials;
    matList.DisplayMember = "Name";
}

private void newMat_Click(object sender, EventArgs e)
{
    AddMaterial form = new AddMaterial();
    if (form.ShowDialog() == DialogResult.OK)
    {
        _materials.Add(form.NewMaterial);
    }
}

(This code assumes that your AddMaterial class adds the new item to the DB and exposes it through a NewMaterial property) (此代码假定您的AddMaterial类将新项目添加到数据库中,并通过NewMaterial属性公开它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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