mechu911
mechu911

Reputation: 426

Can I bind DbSet and BindingList together to display database contents in the ListBox?

I use WinForms and Entity Framework 6. I have an:

  public class ApplicationDbContext : DbContext {
        public DbSet<Person> People{ get; set; }
  }

Every Person has properties: Id,Name,LastName,Age.

In the Form I would like to display all the People in the ListBox and I would like to keep the contents of this ListBox synchronized with the database.

How to bind BindingList bindingList to the ApplicationDBContext context, or the other way around?

Comment: this is SSCCE.

Upvotes: 3

Views: 1679

Answers (1)

ocuenca
ocuenca

Reputation: 39326

You can use the ToBindingList() extension method to get the BindingList<Person> you need as a DataSource in your ListBox:

public partial class YourForm : Form
{
    private YourContext context=new YourContext();

    public BindingList<Person> BindingList { get; set; }


    private void YourForm_Load(object sender, EventArgs e)
    {
        context.People.Load();
        this.listBox1.DataSource= BindingList= context.People.Local.ToBindingList();
        this.listBox1.DisplayMember = "Name";
    }

    //Button for save new changes
    private void SaveChangesButton_Click(object sender, EventArgs e)
    {
        context.SaveChanges();
    }

    //Disposing the context before close the form
    private void YourForm_FormClosing(object sender, FormClosingEventArgs e) 
    { 
        context.Dispose(); 
    } 
}

When an object is added or deleted from the DbSet it will also be added or removed from the BindingList. Adding or Removing from the BindingList will also perform the corresponding Add/Remove on the DbSet.

Upvotes: 1

Related Questions