ASP.NET – Using a DropDownList for Editing in a Data Control

Maybe it's just me but every time I come to do this (usually about every 6 months as I build an ASP.NET demo) I run into problems so I thought I'd give an example here so I can use it again in September :-).

Imagine I have a page that displays a list of houses for sale in a Data Control (I'll use a GridView for simplicity). Perhaps each house has certain properties for which there is a discrete set of acceptable values, eg in my case the "Property Type" (Flat | Bungalow | Castle etc) and the "Town" (Maidenhead | Slough | Windsor etc). When a user switches the Data Control into Edit mode, I want to display the valid options in a DropDownList to assist the user's selection.

The data is coming from a database, the schema for which looks like this:

Database Schema

And I'd like an "Index" view that looks like this (thanks to Andreas Viklund for the template I'm using):

Index View 

And an "Edit" view that looks like this (note the DropDownLists in the row being edited):

Edit View

Of course it would be possible to do this in code but it's also possible to do this declaratively in ASP.NET. I've used SqlDataSource controls for simplicity but take your pick from any of the DataSource controls or roll your own query code. Here's what my GridView looks like – I've highlighted the interesting bits.


GridView Markup

In the EditItemTemplates the DropDownLists point to a DataSource dedicated to querying for the relevant data (ie the list of Towns or HomeTypes). DataTextField / DataValueField allow us to display the TownName / TypeName but use the relevant ID as the DropDownList value. Finally we need to bind the SelectedValue so the initial value of the DropDownList is set correctly and changes are reflected on submit. In the ItemTemplate I just display the field value as text.

My DataSource controls are below:


DataSource Control Markup

Hope that serves as a useful reference for me at least.

Technorati Tags:,databinding