Jaime
Jaime

Reputation: 1192

How do I get a Windows Forms DataGridView to show new records when bound to EntityCollection

Trying to add new records to the EntityCollection at runtime and have the the DataGridView update with the new information.

I have tried bind the datagridview directly to the entity collection (i.e. ObjectSet) and through a BindingSource that is bound to the same collection.

I have tried DataGridView.Refresh(), DataGridView.EndEdit(), and BindSource.ResetBindings() among other things, but nothing seems to work.

Upvotes: 5

Views: 2926

Answers (3)

Abdo
Abdo

Reputation: 14061

I hope it's not too late =) I have something that works here...

// Entity Data Model
private ManagerEntities context = new ManagerEntities();

// declare private member    
private BindingList<Currency> lstCurrencies = null;

// on form load, load data and bind to DataGridView's DataSource

private void Form1_Load(object sender, EventArgs e) {

     lstCurrencies = new BindingList<Currency>();

     ObjectResult or = ((ObjectQuery)currencies).Execute(MergeOption.AppendOnly);
     foreach (Currency c in or)
         lstCurrencies.Add(c);

     // dgMain is my DataGridView
     dgMain.DataSource = lstCurrencies;
}

// this will save objects that have changed. You might want to add logic for newly created and deleted objects.
private void btnSave_Click(object sender, EventArgs e) {
    context.SaveChanges();
}

Upvotes: 0

Hath
Hath

Reputation: 1

I am stuck with same problem. Microsoft should care about the people who use their technology and EF should care about data binding. Jaime, if you find a better way, please update this list. For me, recreating the context instance works fine for me. The funny thing is debugger shows that entity context & binding source has latest updates but datagridview still doesn't refresh. Thanks

Here is the best solution I have found so far -

Basically you need to do

bindingSource.DataSource = EntityContext.Collection
                               .Execute(MergeOption.AppendOnly);

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292685

Try that:

bindingSource.DataSource = null;
bindingSource.DataSource = theCollection;

Alternatively, you could maintain a in-memory copy of the data in a BindingList<T>. Bind the DataGridView to the BindingList, and when you add an entity to the ObjectSet, add it to the BindingList too.

Upvotes: 0

Related Questions