Databind ADO.NET Entity Framework to ListBox

2019-08-06 03:02发布

问题:

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)