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:


<h2>

        Product Dropdown

    </h2>

    <p>

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

    </p>



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";

            ddlProducts.DataBind();

        }


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)

        {

            SetProductDropDown(GetProductsForDropDown());

        }


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!

Enjoy!

4 comments:

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

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

    ReplyDelete
  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

    ReplyDelete