September 14, 2010

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.

C#

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

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
DropDownList1.DataSource = Enumerable.Range(1990, 21).ToList()
DropDownList1.DataBind()
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.

OUTPUT

image



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "Populate a DropDownList with a Sequence of Numbers using LINQ"
  1. Anonymous said...
    September 24, 2010 1:13 PM

    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.

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions