Tuesday, March 22, 2011

Populating an ASP.NET DropDownList control with LINQ and Anonymous Types

Dropdown lists are everywhere, chances are you will never work on a website that does not include at least one dropdown list. Fortunately, with LINQ and Anonymous Types, this could not be easier. Here is a super simple example. I'm using the Adventure Works database for which I have created an EF context.

1. Add a DropDownList control to your page:


        Product Dropdown



        <asp:DropDownList runat="server" ID="ddlProducts" />


2. Next, we'll add a method in the code-behind to grab all the products:

private IQueryable GetProductsForDropDown()


            AdventureWorksEntities db = new AdventureWorksEntities();

            var items = from p in db.Products

                        select new


                            Text = p.Name,

                            Value = p.ProductID


            return items;


As you can see, this method returns an IQueryable. All we are doing is grabbing the Name and ProductID from all products in the table and putting them into an Anonymous Type with 2 properties: Text and Value.

3. Now, we'll create another method that will bind this data to the dropdown list:

private void SetProductDropDown(IQueryable products)


            ddlProducts.DataSource = products;

            ddlProducts.DataTextField = "Text";

            ddlProducts.DataValueField = "Value";



In this method, we're accepting the IQueryable from the previous method and using it as the DataSource for our dropdown list. Next we set the DataTextField property to "Text" and DataValueField property to "Value". These values match the property names on our Anonymous Type, so we're good to go. Finally call the DataBind.

4. Finally, tie it all together with a call in the Page_Load:

protected void Page_Load(object sender, EventArgs e)




5. Run it, and you're done:

View the source here and you'll see the values on the dropdown list are populated with ProductIDs. Pretty simple and fast!



  1. sir i want help in my asp project. will u help me. i m developing my college project.

  2. Hey Prashant, which type of help you want in your ASP project? Are you working in .NET Development Company?

  3. I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.
    usb drive recovery

  4. I got the following error when attempting your suggestion:

    System.NotSupportedException: 'Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery, DbRawSqlQuery) is not supported. Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data. ...
    For ASP.NET WebForms you can bind to the result of calling ToList() on the query or use Model Binding, for more information see http://go.microsoft.com/fwlink/?LinkId=389592.'