Compartilhar via


ASP.NET 2: DetailsView Control containing a DropDownList in Edit Mode, bound to a DataSource

ASP.NET About a year ago I wrote up an explanation for how to change the Edit Mode for one of the fields in ASP.NET 2.0 GridView so that it would contain a DropDownList rather than a TextBox.  That way, for something like a State or County column, you could limit entries to only acceptable values.

I got asked if you could use a DataSource for the options displayed by the DropDownList instead of the baked-in list of items that I showed in the previous blog entry.

The answer of course is yes. :)

One way to accomplish this visually is to create a DropDownList, configure a new (i.e. a second) DataSource for it that contains the entries you want, and then steal the code from there.  Here is an example that uses (and includes) the Northwind database.

It's always nice to know that the magic of search engines means that people still get tips out of my writing from back almost a year ago!

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"DataSourceID="SqlDataSource1">
   <Columns>
      <asp:CommandField ShowEditButton="True" />
      <asp:TemplateField HeaderText="ProductName" SortExpression="ProductName">
         <EditItemTemplate>
            <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="ProductName" DataValueField="ProductName" SelectedValue='<%# Bind("ProductName") %>'>
            </asp:DropDownList>
            <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [ProductName] FROM [Products]"></asp:SqlDataSource>
         </EditItemTemplate>
      <ItemTemplate>
...

 

There are some useful links for learning more about ASP on the sidebar of my blog.