The base ListControl class is the base class for controls
like DropDownList, RadioButtonList, CheckBoxList, etc. This control has the
ability to manually add items to the list, as well as supporting data binding
the items into the collection.
The ListLabel control is a custom control that plugs into
the existing framework for creating list controls; however, instead of
rendering an interface that has to be manipulated, it simply renders the item
that is stored in the collection marked as selected. Selection occurs in many
ways in the ListControl base class, either through the SelectedIndex or
SelectedValue properties. And because that is also handled for us, the
following approach is very simple to use to render the content out to the
screen.
Listing 1
protected override void Render(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
if (!this.DesignMode)
{
//Get the selected item
ListItem item = this.SelectedItem;
//If the item exists, write out the text value
if (item != null)
writer.Write(item.Text);
else
writer.Write(this.EmptyDisplayText);
}
//Else in design mode, then render specific texts
else
{
//If bound using a data source ID, write that it is bound
if (this.DataSourceID != null)
writer.Write("Databound");
//Else write the ID
else
writer.Write("[" + this.ID + "]");
}
}
The following code gets the selected item in the list. If no
selection exists (SelectedIndex equals -1), the response of the
EmptyDisplayText value is written, which is a string that simply takes a descriptive
message to display. This method also takes care of handling design mode, by
writing a Databound message when the databinding has been setup in the
designer, or by simply writing the ID of the control otherwise.
This control is optimal to be used in view mode of a
GridView, where edit mode will be using a DropDownList or RadioButtonList.
Listing 2
<asp:GridView ..>
<Columns>
<asp:TemplateField HeaderText="State">
<ItemTemplate>
<cc1:ListLabel id="lblState" runat="server"
DataSourceID="sdsStates"
SelectedValue='<%# Eval("StateCode") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList id="ddlState" runat="server"
DataSourceID="sdsStates"
SelectedValue='<%# Eval("StateCode") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>