我可以将DbSet和BindingList绑定在一起以显示ListBox中的数据库内容吗?

时间:2015-06-14 15:50:00

标签: c# winforms entity-framework listbox

我使用WinForms和Entity Framework 6.我有一个:

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

每个Person都有属性:IdNameLastNameAge

Form我希望显示People中的所有ListBox,并且我希望将此ListBox的内容与数据库保持同步。< / p>

如何将BindingList bindingList绑定到ApplicationDBContext context,或者反过来?

评论:这是SSCCE。

1 个答案:

答案 0 :(得分:0)

您可以使用ToBindingList()扩展程序在BindingList<Person> DataSource中获取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(); } }

DbSet

BindingList添加或删除对象时,也会在BindingList中添加或删除该对象。添加或删除DbSet也会在get_client_ip_server()上执行相应的添加/删除。