Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at
DropDownField for GridView

One of the requirements on my current project involves the user defining what a grid of data should look like. We allow a user to create a "definition", which we persist in the database and then we construct a GridView at runtime based on the "definition". This mean that we don't know what fields (or even types of fields) the GridView has at design time. Additionally, we needed to support drop down lists in the GridView.

I searched for a good while hoping to find out how to programmatically add a drop down list to a GridView. All of the examples I found used a TemplateField and were based on the assumption that you knew you wanted a drop down list at design time. So I decided to build my own custom drop down list field. Reflector allowed me to dissect the various fields that shipped with the framework (BoundField, CheckBoxField, etc.) All of these classes derive from DataControlField. I won't go into too much more detail for the moment, but the major members that I had to implement for DataControlField were:

  • InitializeDataCell
  • OnDataBindField

InitializeDataCell determines the state of the current row in the GridView (is it edit or readonly). Then it instantiates the appropriate controls. In my case, the default DataControlFieldCell for read-only and a (you guessed it) DropDownList for edit. Additionally, it wires up the DataBinding event for the control it just added.

OnDataBindField is responsible for putting the right value in the control. In my case, we check to see whether or not we have a drop down list and if we do, then we apply some logic to populate the items in that list. An interesting point here is that you want to instantiate new ListItems for every row. If you only have one set of ListItems you will end up with odd behavior, because multiple DropDownLists will be referencing the same exact ListItems.

Posted 09-19-2006 9:33 PM by Christopher Bennage


About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Google Reader or Homepage Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of
Red-Gate Tools For SQL and .NET


SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
NHibernate Profiler
Balsamiq Mockups
JetBrains - ReSharper
Web Sequence Diagrams
Ducksboard<-- NEW Friend!


Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers


Community Server (Commercial Edition)