欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

EF对DropDownList绑定数据

程序员文章站 2022-06-11 23:53:58
...

先拉一个控件:DropDownList

<asp:DropDownList ID="ddl_Class" runat="server"  CssClass="form-control"></asp:DropDownList>

后台代码展示:

  using (var db = new DemoEntities())
                {
                    //1.查询出当前修改的学员信息
                    var model = db.Student.FirstOrDefault(s => s.Id == editId);
                    if (model != null)
                    {
                        //2.绑定学员信息到界面上
                        txt_Name.Text = model.Name;
                        txt_Age.Text = model.Age.ToString();
                        txt_Email.Text = model.Email;
                        txt_Mobile.Text = model.Mobile;

                        //3.查询出班级信息

                        //3.1.查询班级数据
                        var list = (from c in db.Class select c).ToList();
                        //3.2.将数据绑定到下拉框
                        ddl_Class.DataSource = list;
                        ddl_Class.DataTextField = "ClassName";
                        ddl_Class.DataValueField = "Id";
                        ddl_Class.DataBind();

                        //4.使班级下拉框选中当前学员的班级
                        ddl_Class.SelectedValue = model.ClassId.ToString();

                    }
                    
                }

运行结果: