Check Out Dave's New game for iPhone and iPod Touch: Smiled Out!

Archive for December, 2009

Binding a Dropdown List in ASP.Net Inside a ListView

Posted in CSharp, Dot Net on December 8th, 2009 by Dave Andrews – 3 Comments

I like to blog things that I have to look up. Here’s a quickie which solves a problem I was having.

In my table, I have a field “PayType” which is a char(1) and has valid values “S” and “H”. These mean “Salary” and “Hourly”, respectively.

I am showing this in a ListView in my screen I’m developing. So, when editing the record, I naturally wanted a dropdown box where you can choose “Hourly” or “Salary”. Note this will only work if you know what values you want in your dropdown box. If the selections are dynamic, then you will probably have to have a databound event and build the box manually.

I wanted it to default to the selected type for the record I’m editing when I click on edit, but could not find anything in the intellisence that looked correct for my Bind() call.

1
2
3
4
5
6
7
<asp:DropDownList 
      ID="ddPayType" 
      runat="server" 
      SelectedValue=<%# Bind("PayType") %>  >;
          <asp:ListItem Text="Salary" Value = "S" />
          <asp:ListItem Text="Hourly" Value = "H" />
</asp:DropDownList>

The answer was to Bind on the “SelectedValue” parameter. I was thrown off because SelectedValue does not seem to pull up in Visual Studio 2008 as an option on the list when writing code in the markup editor. But it correctly updates the value when the Update command is executed.