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.



About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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.