binding winforms to database by entity framework 6

.net c# entity-framework entity-framework-6 winforms


The scenario is simple:

  1. I have EF6 DbContext MyDbContext
  2. I have Form with ListBox
  3. The code to bind data from DB to listbox is as follows:

    dbContext = new MyDBContext();
    listBox1.DataSource = dbContext.Experiments.Select(a => a.Name + "," + a.ModificationDate.Second).ToList();
  4. I have button to Add a row to DB table with code:

     dbContext.Experiments.Add(new Models.Experiment()
            CreationDate = DateTime.Now,
            ModificationDate = DateTime.Now,
            Description = "Test" + DateTime.Now.Second,
            Name = "test" + DateTime.Now.Second

Now I would like to automatically refresh positions in my listbox. What is the best approach to do that? I know that I can rewrite code from point 3 but I would like to have it all two way binding and automatically updated

12/31/2014 1:12:15 PM

Popular Answer

I think that "data binding" is a keyword here. Generally in WinForms two way bidning is provided by classes like BindingList<T> or BindingSource. The question is how to use them together with EF. I think that an extension method ToBindingList can be useful here. However, I don't have a lot of experience with using it. I suggest you to look at the following article: Entity Framework Databinding with WinForms. Besides, if you search for ToBindingList EntityFramework on stackoverflow you will find many related questions.


I made a small test and I see a potential problem. The automatic synchronization between a control and EF will work if you use the same data context (the same instance of DbContext class). It means that a context may have a long life-cycle what is not recommended.

12/31/2014 2:17:19 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow