Accessing ASP.NET DropDownList Items from Code behind

Couple days ago I was writing an ASP.NET webform and I wanted to programmatically inspect the items in the drop down. The drop down list in the ASP.NET page looks something like this:

<asp:dropdownlist id="mydropdown" class="dropbox" runat="server">
  <asp:listitem text=" -- select -- " value="" />
  <asp:listitem text="Text 1" value="1" />
  <asp:listitem text="Text 2" value="2" />
  <asp:listitem text="Text 3" value="3" />
</asp:dropdownlist>

and then in the code behind (like I mentioned before) you can do a bunch of useful things. First, if I wanted to set the default selected item in the form, I’d write this:

public void Page_Load(Object sender, EventArgs e) {
  // initialize form
  if (!IsPostBack) {
   mydropdown.SelectedValue = "1";
  }
}

That’s relatively trivial, it gets more interesting when you consider that you can access the DropDownList items programatically:

foreach (ListItem l in mydropdown.Items) {
  if (l.Value == 1) {
   l.Selected = true;
  }
}

In the above example I use the foreach statement to iterate through the collection of ListItems in the Items property. If the Value property of the ListItem is 1, then I set that to be selected. You can also access the Text property of the List Item.

The C# foreach construct jogged my memory about Java 1.5 (Tiger) which is supposed to have enhanced ‘for’ loops (also read this); for example this:

for (Iterator i = c.iterator(); i.hasNext(); ) {
  // do stuff with 'i'
}

becomes this:

for (Object o : c) {
  // do stuff w/ 'o'
}

When is 1.5 gonna arrive?

This entry was posted in .NET. Bookmark the permalink.

2 Responses to Accessing ASP.NET DropDownList Items from Code behind

  1. Brian says:

    ASP.Net 2 is just around the corner..

  2. AJ says:

    Yeah, I actually was asking when Java 1.5 was gonna be here.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>