Among the ASP.NET questions I received was one (out in Galway) where someone asked if it's possible to customize the input controls used to enter values into a GridView or DetailsView control.  Specifically, I was asked if you can present a DropDownList control instead of a TextBox to for an input control.

I knew it was possible, but what I didn't know was whether it could be pulled off using only declarative code.  It turns out you sure can.  ASP.NET 2.0 rocks!

What I needed to do was this:

  • Convert the BoundField into a TemplateField.  (One way to do this is via the "Edit Fields..." option on the DetailsView Common Tasks menu.  Select "Convert this field into a Template Field".)
  • Modify the resulting TemplateField's EditItemTemplate so that it contains a DropDownList control with:
    • the DataTextField and DataValueField Properties set, and
    • the SelectedValue bound to the appropriate field, as in: <%# Bind("FieldName") %>

If you want to try this yourself, you might try modifying the Olive website (link goes to where it's hosted at NIMTUG.)  (Olive looks much like the results of what we built in Belfast, Cork and Galway.)  For instance, you could constrain the State selection on DataView.aspx so that the user can only select valid state acronyms. The salient bits would look something like this:

<asp:DetailsView ID="DetailsView1" Runat="server" DataSourceID="ObjectDataSource1"AutoGenerateRows="False" ForeColor="Black" CellPadding="2" BorderColor="Tan" GridLines="None" BorderWidth="1px" BackColor="LightGoldenrodYellow">
<asp:BoundField HeaderText="ID" DataField="ID" SortExpression="ID"></asp:BoundField>
      <asp:BoundField HeaderText="Name" DataField="Name" SortExpression="Name"></asp:BoundField>
      <asp:BoundField HeaderText="LastName" DataField="LastName" SortExpression="LastName"></asp:BoundField>
      <asp:TemplateField SortExpression="State" HeaderText="State" >
            <asp:DropDownList DataTextField="State" DataValueField="State" ID="DropDownList2" Runat="server" SelectedValue='<%# Bind("State") %>' >
         <ItemTemplate >
            <asp:Label Runat="server" Text='<%# Bind("State") %>' ID="Label1"></asp:Label>

[Update: You can also bind the contents of the DropDownList's ListItems to a DataSource if you'd like (so that, for example, the states above come out of a database as opposed to a baked-in list).  If you want to do it visually, just create a DropDownList, configure its DataSource, and then steal the code from there.  Here is an example that uses the Northwind database.]