简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM