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:
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.
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.
09-19-2006 9:33 PM