C#实体框架从组合框获取数据

时间:2017-01-08 18:30:13

标签: c# entity

            private void Submit_Click(object sender, EventArgs e)
{
                ScoutContext db = new ScoutContext();
                ScoutData cust = new ScoutData();
                cust.FName = textBox1.Text;
                cust.LName = textBox2.Text;
                cust.FName = textBox3.Text;
                cust.FaWork = textBox4.Text;
                cust.MoName = textBox5.Text;
                cust.MaWork = textBox6.Text;
                cust.PlaceOfBirth = textBox7.Text;
                cust.City = textBox8.Text;
                cust.School = textBox9.Text;
                cust.FaceBook = textBox10.Text;
                cust.Phone = textBox11.Text;
                cust.MPhone = textBox12.Text;
                cust.IDNumber = textBox13.Text;
                cust.NOfQaid = textBox14.Text;
                cust.GroupID = ?????????????????


                db.SaveChanges();
}

我在Windows窗体上工作,我有这个数据,用户填写文本框,之后我需要将数据保存到我的上下文(数据库),这是我的代码将数据插入我的数据库,但我有用户将从ComboBox中选择的数据(数字和一些字符串)。我需要获取这些数据并将其保存到对象列表中,这是代码:

 public class Groups
    {
        [Key]
        public string GroupsID { set; get; }

        public string NameOfGroup { set; get; }
        ***public virtual List<ScoutData> Members { set; get; }***
    }

背景信息:

  public class ScoutContext : DbContext
    {
        public ScoutContext()
            : base("Scout")
        {
        //    if (!Database.Exists("ScoutData"))
        //        Database.SetInitializer(new DropCreateDatabaseAlways<ScoutContext>());
        }
        public DbSet<ScoutData> ScoutDatas { set; get; }
        public DbSet<Groups> GroupesScout { set; get; } 
    }

我需要从组合框到成员列表中获取此数据并将其保存到对象列表(成员)

1 个答案:

答案 0 :(得分:0)

这取决于你在组合框中的含量。

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var combo = sender as ComboBox;

    // If combobox has ScoutData then do this
    var item = combo.SelectedItem as ScoutData;

    // If combobox has something else then do this
    var item2 = combo.SelectedItem as SomeThingElse;
    var newScout = new ScoutData { FName = item2.FName /*, etc, etc */  };

    // Then add it to your list
}