Databind ADO.NET Entity Framework to ListBox

…衆ロ難τιáo~ 提交于 2019-12-11 06:34:17

问题


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

回答1:


That's because db.Materials doesn't raise a notification when an item is added to it. You should use a BindingList<T> as the 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)



来源:https://stackoverflow.com/questions/3516916/databind-ado-net-entity-framework-to-listbox

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