Combobox,BindingSource,WinForms - 以一对多关系添加新条目

时间:2017-12-01 08:51:14

标签: c# winforms combobox bindingsource


我有与人模型一对多的公司模型。
我想添加新的Person,在组合框中,我希望能够从公司中选择公司,所有这些都使用bindingsource。当我列出所有人时我有PeopleForm,并且在此表单中我添加了新的Person按钮。在PersonForm我有文本框和组合框与公司列表。

首先我设置bindingsources:

BindingList<Company> companiesList = new BindingList<Company>();
    private void PoepleForm_Load(object sender, EventArgs e)
    {
        using(Ctx ctx = new Ctx())
        {
            personBindingSource.DataSource = ctx.People.ToList();
            foreach (Company company in ctx.Companies)
            {
                companiesList.Add(company);
            }
        }
    }

这是我的按钮添加人事件:

private void button1_Click(object sender, EventArgs e)
        {
            PersonForm personForm = new PersonForm()
            {
                MdiParent = this.MdiParent,
                person = new Person(),
                companiesList = companiesList
            };

            personForm.FormClosing += delegate
            {
                if (personForm.DialogResult == DialogResult.OK)
                {
                    using (Ctx ctx = new Ctx())
                    {
                        personBindingSource.Add(personForm.person);
                        ctx.People.Add(personForm.person);
                        ctx.SaveChanges();
                        personBindingSource.ResetBindings(false);
                    }
                }
            };
            personForm.Show();
        }


PersonForm加载事件:

private void PersonForm_Load(object sender, EventArgs e)
        {
            personBindingSource.DataSource = person;
            companyBindingSource.DataSource = companiesList;
        }

班级公司:

public class Company
{
    public Company()
    {

    }
    public int Id { get; set; }
    public string Name { get; set; }
    public int NIP { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public int Code { get; set; }
    public int Phone { get; set; }
    public string Notes { get; set; }

    public virtual ICollection<Person> Person { get; set; }

}

班主任:

public class Person
    {
        public Person()
        {

        }
        public int PersonId { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public string Job { get; set; }
        public int Phone { get; set; }
        public int Mobile { get; set; }

        public virtual Company Company { get; set; }
    }

在PersonForm中,我使用设计器添加文本框,所有文件框都将绑定设置为personBindingSource。我应该在组合框中设置哪些来源以在其中包含公司列表并且将两个元素(文本框和组合框选定值)连接起来。我试图理解bindingsource背后的魔力。

0 个答案:

没有答案