ASP.NET Binding a DropdownList


3/14/2010 6:00:00 PM

This tutorial was designed to show you how to create a list of strings and bind it to a drop down list in asp.net.

First we must create a DropDownList and place it in the front end of our web page. you can do this by dragging a DropdownList from the tool box onto your page. You should then see the following code on your page:


Name your DropDownList something appropriate. In my case I will be using a list of strings with different types of Dinosaurs:

 

Now we are ready to talk to our DropDownList in our code behind. first we want to create a list of strings:

List dinosaurList = new List();

Once we have our empty list of Dinosaurs created we can start adding Dinosaur names to the list:

dinosaurList.Add("Triceratops");
dinosaurList.Add("Stegosaurus");
dinosaurList.Add("Indosaurus");
dinosaurList.Add("Plateosaurus");
dinosaurList.Add("Tyrannosaurus Rex");
dinosaurList.Add("Brontosaurus");

Once we have added all of our Dinosaurs to our list we can then bind the list to the DropDownList control:

dinosaurDropDownList.DataSource = dinosaurList;
dinosaurDropDownList.DataBind();

The complete code segment will look like:

List dinosaurList = new List();

dinosaurList.Add("Triceratops");
dinosaurList.Add("Stegosaurus");
dinosaurList.Add("Indosaurus");
dinosaurList.Add("Plateosaurus");
dinosaurList.Add("Tyrannosaurus Rex");
dinosaurList.Add("Brontosaurus");

dinosaurDropDownList.DataSource = dinosaurList;
dinosaurDropDownList.DataBind();

If you fire up your Web application now you should see the DropDownList on your web page with your list of strings.