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:
2. Next, we'll add a method in the code-behind to grab all the products:
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:
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:
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!