I need the DetailsView to display in 3 modes, namely Insert, Edit and ReadOnly. For Insert and Edit modes, a DropDownList takes care of getting the values from the referenceDataSource. However, in ReadOnly mode, I do not want to introduce the DropDownList, for it would have unnecessarily bloat the ViewState and post-back values.
A label should be all that is needed to display, but what do I type to data bind the label to the referenceDataSource? Most of the time, I end up casting the Eval to a DataRowView, getting the Row, and calling GetParentRow. However, that is not a general solution that can be applied everywhere. By changing the data source to use DataReader instead of DataSet, the code in the label will break.
So I decided to roll out my own server control. Taking reference from Creating a Databound Label Control, I created a label control that takes similar attributes as DropDownList, so that all that is needed is to copy the DropDownList from the EditItemTemplate, paste it in ItemTemplate, and changing the tag to ReferenceLabel.
Neat huh? Below is the code for the ReferenceLabel. Place it in App_Code and add the following into Web.config.
Due to the aim of reducing ViewState, only the initial selected text is stored in the ViewState. Changing the SelectedValue after the control has been data bound will not change the displayed text.