Populate a DropDownList with a Sequence of Numbers using LINQ

Let us assume you want to populate a DropDownList with ‘Years’ data ranging from 1990 to 2010. The LINQ Range Operator is extremely useful in such situations to quickly generate a sequence of numbers. Here’s how to populate an ASP.NET DropDownList with a Sequence of Numbers using a single line of LINQ code.


protected void Page_Load(object sender, EventArgs e)
DropDownList1.DataSource = Enumerable.Range(1990, 21).ToList();


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
DropDownList1.DataSource = Enumerable.Range(1990, 21).ToList()
End Sub

As you can see, we use the Enumberable.Range method to generate a sequence of integers within a range and then bind the DropDownList to the list of integers.



Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

Anonymous said...

That is the coolest thing I've seen today. Thanks for the great information on this site. It's become my go-to site for .net.