简体   繁体   中英

Populate a DropDownList using Entity Framework 4

I need a very simple example of code to populate a DropDownList using Entity Framework 4.

At the moment I use this code:

        using (TestHierarchyEntities context = new TestHierarchyEntities())
        {
            uxSelectNodeDestinationDisplayer.DataSource = context.CmsCategories.ToList();
            uxSelectNodeDestinationDisplayer.DataBind();
        }

But it does not work properly... Any idea? Thanks

Something like this should work :

using (TestHierarchyEntities context = new TestHierarchyEntities())
        {
                var category = (from c in context.context
                                select new { c.ID, c.Desc }).ToList();

                DropDownList1.DataValueField = "MID";
                DropDownList1.DataTextField = "MDesc";
                DropDownList1.DataSource = category;
                DropDownList1.DataBind();                
         }
using (dbEntities db = new dbEntities())
{
    ddlNewEmployee.DataSource = (from emp in db.CC_EMPLOYEE
                                    select new { emp.EmployeeID, emp.EmployeeCode }).ToList();

    ddlNewEmployee.DataTextField = "EmployeeCode";
    ddlNewEmployee.DataValueField = "EmployeeID";
    ddlNewEmployee.DataBind();
}

This works perfectly:

private COFFEESHOPEntities1 CoffeeContext = new COFFEESHOPEntities1();
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //getData();
        cbxCategory.DataSource = CoffeeContext.tblProductTypes.ToList();
        cbxCategory.DataTextField = "Description";
        cbxCategory.DataValueField = "ProductType";
        cbxCategory.DataBind();
    }
}

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