views:

17

answers:

1

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

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)

Thomas Levesque
I like your solution, however is there an easier way? Shouldn't the entity framework raise an event when an item is added?
WedTM
Well, db.Materials is not exactly a collection, it's a query. You don't "add" items to it: you add them to the database, and the next time you execute the query, the new items will be returned. So it wouldn't make sense to raise a notification in that case
Thomas Levesque