Creating Custom Label Controls
page 3 of 6
by Brian Mains
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 27457/ 45

ListLabel Control

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)
  if (!this.DesignMode)
   //Get the selected item
    ListItem item = this.SelectedItem;
    //If the item exists, write out the text value
    if (item != null)
  //Else in design mode, then render specific texts
    //If bound using a data source ID, write that it is bound
    if (this.DataSourceID != null)
    //Else write the ID
      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 ..>
    <asp:TemplateField HeaderText="State">
        <cc1:ListLabel id="lblState" runat="server" 
        SelectedValue='<%# Eval("StateCode") %>' />
        <asp:DropDownList id="ddlState" runat="server"
        SelectedValue='<%# Eval("StateCode") %>' />

View Entire Article

User Comments

Title: fert   
Name: fo kos
Date: 2012-12-10 8:56:24 AM
fo kos kos ley kos
Title: Nice Addition   
Name: Michael Davey
Date: 2007-11-29 8:46:40 AM
Neat additions to the label control.. thanks!

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2021  |  Page Processed at 2021-02-27 4:54:45 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search