Pad A String In JavaScript Using Augmentation

Ever needed to pad a string in JavaScript with a certain character? This article will describe a simple extension to the String prototype that will do just that! -Perhaps with a bit more flexibility.

To get right to the point, here is the implementation:

if ( "undefined" === typeof String.prototype.pad ) {
    String.prototype.pad = function _String__pad ( obj ) {
        var result = this,
            width = 2,
            padChar = "0",
            prefix = false;

        if ( obj ) {
            if ( "object" === typeof obj ) {
                if ( obj.prefix ) { prefix = obj.prefix };
                if ( obj.width ) { width = obj.width };
                if ( obj.char ) { padChar = obj.char };
            } else if ( "string" === typeof obj ) {
                padChar = obj;
            } else if ( "number" === typeof obj ) {
                width = obj;
            }
        }

        while ( this && width > result.length ) {
            if ( prefix ) {
                result = padChar + result;
            } else {
                result += padChar;
            }
        }

        return result;
    };
}

Before I get to the guts of the above code snippet, I wish to examine a few reasons it is possible:

  • Instance methods can be created on-the-fly. This means a String object such as “Hello World” would immediately contain the above method named “pad”. The method could be called like “Hello World”.pad().
  • JavaScript is a dynamic language. In this case, it means any variable can be of any type at any point during runtime.
  • A method exists as a “function”. This can be explicitly tested.
  • Instance methods exist in an Object’s prototype.

Now for the details.

First, it is always wise to make sure your code is not performing unnecessary work. To this end a check is made to make sure the function does not already exist on String’s prototype. If it does not already exist, it is created.

Four variables are then declare presenting the features of this method:

  • Returns a new string
  • Supports a custom string width
  • Supports a custom padding character
  • Supports either prefix padding or suffix padding

These variables are optionally overridden by the object, String, or Number argument given. This is one of many times when the beauty of JavaScript’s weakly-typed nature really shines. Any of the features can be overridden given the appropriate argument type and value. If the argument is an object, the method expects the object to contain the three properties: prefix, width, and char. If the argument is a String the method assumes the client is attempting to override the padding character. If the argument is a number, the method assumes the client is attempting to override the padded string width.

Lets talk more about the padded string width. This is important for the next bit of code.

Assume there is a string indicating an order number of “99D”. The requirements say order numbers less than 5 characters must be padded on the left with zeros. The implementation supports this:

"99D".pad({ char: "0", width: 5, prefix: true }); //result: "0099D"

-or-

var orderNumber = "99D";
orderNumber.pad({ char: "0", width: 5, prefix: true }); //result: "0099D"

-or-

var padOptions = { char: "0", width: 5, prefix: true };
"99D".pad(padOptions); //result: "0099D"

To get this set width, a while loop is used. While the string is less than the given width, the method adds the specified pad character to either the beginning or the end of the string based on whether it should be a prefix or not. Once the string is at least the length of the specified padded string width, the method breaks out of the while loop and returns the resultant string.

There are other ways to use this implementation of the pad method as well:

Specify the padding character -

"E".pad("T"); //result: "ET"

Specify the padded string width -

"1".pad(2); //result: "10"

There are a few improvements or additional features that could be implemented for this method but, this is a flexible start.

Dynamic Objects Using WinJS & XML

Welcome to the latest Creationism article. The Creationism series focuses on various constructs using common Microsoft technologies. This entry will show how to create a JavaScript object based on an xml file. The article will assume basic JavaScript, WinJS and XML experience. This post originated from my blog on Code Project: “Creationism: Dynamic Objects Using WinJS & XML“.

The Problem

I am writing an app for Windows 8 and need a maintainable set of values I can use in JavaScript. My first attempt included creating a Constants object that contained the values I needed. This soon became unmanageable as the number of constants increased. To fix this, something like an ASP.Net web.config file would be great. The problem is I do not want the restriction of accessing it through a sort of “AppSettings” property as with ASP.Net websites. My preference would be a JavaScript object that contains the properties I need but from a configuration file. How would I do this?

The Solution

What would solve my problem is a JavaScript object created at runtime that includes properties and values based on an XML file. A few things known about JavaScript make this solution viable:

  1. JavaScript is a highly dynamic language. Considering this fact, creating an object during runtime should be like Eddie Van Halen playing a guitar.
  2. Object properties can be accessed and manipulated using normal array syntax.
  3. Server data is accessible from JavaScript. AJAX is the acronym.
  4. Since an XML file is obtained, it can be parsed no differently than an average HTML document.

Combining the implementation of these four facts will enable me to create an object at runtime using the data of an XML file. The next section will explain how this is done.

The Implementation

There are three basic steps to implementing this. The mechanisms accessible from WinJS will help tremendously. First, the XML file needs to be obtained. This can be done using the WinJS.xhr function. More information on this function can be found on MSDN: “WinJS.xhr function (Windows)”. The next step is to parse the XML file and then to create the Constants object based on the data retrieved from the file. These steps will be explained in more detail in the following sections.

The Configuration File

To consume the file, the file will need to be created. Below is the sample content in the file:

<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
  <Constant1>
    <add name="String" value="Value 1" />
    <add name="Integer" value="1" />
  </Constant1>
  <Constant2>
    <Boolean>
      <add name="IsTrue" value="true" />
      <add name="IsFalse" value="false" />
    </Boolean>
  </Constant2>
  <Constant3>
    <add name="SubConstant" value="SubValue" />
    <NextSubConstant>
      <add name="NextSub" value="NextSubValue" />
    </NextSubConstant>
  </Constant3>
</Configuration>

As can be seen, this is nothing more than an average XML file. There are various nested nodes and attributes to show some of the possible node structures supported by this solution. For this article, the name of the file is “config.xml” and the root node is “Configuration”.

The Data

The WinJS.xhr function is used to get the XML file. This function takes an object used to configure the request and returns a Promise. This is shown below:

WinJS.xhr({
    url: "config.xml",
    headers: {
        "If-Modified-Since": "Wed, 2 Feb 2000 11:11:11 GMT"
    },
    responseType: "document"
}).done(function(result) {
    if (result.status === 200) {
        var data = result.responseXML;
        var root = data.querySelector("Configuration");

        WinJS.Namespace.define("ST.Constants");
        iterate(root, ST.Constants);
    } else {
        /* ... Handle missing document ... */
    }
});

Overview

Above shows what could be thought of as jQuery AJAX on steroids. The xhr function is called taking an object used to configure the XMLHttpRequest. “url” is the only required property. Other optional properties can be used to further configure the XMLHttpRequest. This is much like jQuery’s ajax method but, in this case, a Promise object is returned. The “done” method of the returned Promise is used to process the returned XML document.

Configuring the XMLHttpRequest

WinJS.xhr({
    url: "config.xml",
    headers: {
        "If-Modified-Since": "Wed, 2 Feb 2000 11:11:11 GMT"
    },
    responseType: "document"
})

The parameter passed to the xhr function is an object. This object is used to configure the XMLHttpRequest as mentioned previously. Here the “url” is set to the path to the XML file. Then, the “headers” property is used which includes the “If-Modified-Since” date. This ensures the XML file is obtained. The last property is “responseType” which is used to make sure the result of this call is a document able to be parsed by JavaScript.

Processing the XML File

.done(function(result) {
    if (result.status === 200) {
        var data = result.responseXML;
        var root = data.querySelector("Configuration");

        WinJS.Namespace.define("ST.Constants");
        iterate(root, ST.Constants);
    } else {
        /* ... Handle missing document ... */
    }
});

The next step is to process the returned XML file. The xhr function returns a Promise object. This object contains a “done” method that can be used for processing the results of the xhr function call. As with average use of XMLHttpRequests, the first step is to make sure it succeeded. Using the result passed into the done handler, the status of the request can be determined. This result object is the XMLHttpRequest. It contains useful properties among these being “status” and “responseXML”. A successful status is 200. If the status is 200, the function proceeds with processing the results by first getting the responeXML from the result object. Since the responseType was set to “document”, the content of responseXML is the XML document that can be parsed by JavaScript. The iteration of this document will be described in more detail below but there are two more steps to do first. The iteration method takes two parameters. The first parameter is the node to process. To begin, the root node needs to be processed so this is what is retrieved. The second parameter is the object to process with the node. The object is meant to be static so the WinJS.Namespace.define method is used to create this. The two parameters are passed to the iterate method. The next section provides more detail.

The Iteration

There is hair, teeth, flesh and bones but the iteration method is the meat. Within this method is the traversal of the XML file along with the additions to the Constants object. Below is the implementation:

function iterate(node, ns) {
   if (node && node.childNodes) {
      if (node.childNodes.length > 0) {
         var nodes = node.childNodes;
         var len = nodes.length;
         for (var i = 0; i < len; i++) {
            var sub = nodes[i];
            if (sub.nodeType === sub.ELEMENT_NODE) {
               var name = sub.nodeName;
               if (sub.childNodes.length > 0) {
                  ns[name] = {};
                  iterate(sub, ns[name]);
               } else {
                  var attName = sub.getAttribute("name");
                  var attValue = sub.getAttribute("value");
                  //Key/Value Attribute
                  if (attName && attValue) {
                     ns[attName] = attValue;
                  //Node Name/Value
                  } else if (attValue && node.nodeName && !attName) {
                     ns[name] = attValue;
                  } else {
                     /* ... Handle Data Not Available ... */
                  }
               }
            }
         }
      } else if (node) {
         var name = node.nodeName;
         var attName = node.getAttribute("name");
         var attValue = node.getAttribute("value");
         //Key/Value Attribute
         if (attName && attValue) {
            ns[attName] = attValue;
            //Node Name/Value
         } else if (attValue && node.nodeName && !attName) {
            ns[name] = attValue;
            //Log Warning
         } else {
            /* ... Handle Data Not Available ... */
         }
      }
   }
}

Above is the implementation of the iteration method. This method has various validation checks for the current node, child nodes, and attributes. There is also room for handling missing data.

Handling No Children

The method begins by checking whether the given node and its children exist. If any children exist, it continues processing the child nodes. If there are no children, the method checks to make sure there is a node and upon success attempts to get the name and value attributes. This is shown below:

else if (node) {
   var name = node.nodeName;
   var attName = node.getAttribute("name");
   var attValue = node.getAttribute("value");

   //Key/Value Attribute
   if (attName && attValue) {
      ns[attName] = attValue;

      //Node Name/Value
   } else if (attValue && node.nodeName && !attName) {
      ns[name] = attValue;

      //Log Warning
   } else {
      /* ... Handle Data Not Available ... */
   }
}

There are three possible paths than can be taken here:

  1. If both the name and value attributes exist, the Constants object is updated. A new property is added to the object. This part takes advantage of the fact JavaScript object properties can be accessed and manipulated by using normal array syntax. The new property is created with the value of the “name” attribute and is assigned the value of the “value” attribute.
  2. If the value attribute and node name exist but not the name attribute, the Constants object is updated using the node name. The name of the new property is the name of the node. The value of this new property is the value of the value attribute.
  3. If neither of the above two cases exist, there is no data available as this solution is currently implemented. This is a good place to handle such a case by either logging the occurrence, adding default data, or any other way that is necessary.

Handling with Children

If the given node exists with children, the iterate method proceeds by processing the child nodes. The snippet below shows this:

if (node.childNodes.length > 0) {
   var nodes = node.childNodes;
   var len = nodes.length;
   for (var i = 0; i  0) {

            ns[name] = {};
            iterate(sub, ns[name]);
         } else {

            var attName = sub.getAttribute("name");
            var attValue = sub.getAttribute("value");

            //Key/Value Attribute
            if (attName && attValue) {
               ns[attName] = attValue;

               //Node Name/Value
            } else if (attValue && node.nodeName && !attName) {
               ns[name] = attValue;

            } else {
               /* ... Handle Data Not Available ... */
            }
         }
      }
   }
}

The node is checked to make sure it has child nodes. If it does, each child node is processed in a simple for loop. The current child node is stored and then a check is done to be sure it is an element node. If so, the method checks this node’s children. If they exist, the name of the sub node is used to create a new property of the given Constants object. Then the iterate method is called again this time passing in the current child node and the new property of the Constants object. This provides the support needed to add nested nodes in the XML file.

If the current child node does not have any children, it is processed in the same way as what was described in the previous section “Handling No Children”.

The Outcome

As you are probably aware by now, this solution creates an object at runtime. Using the Watch window while debugging the structure of the object can be seen:

This shows that the structure of the Constants object mirrors the structure of the XML file.

Originally Perceived Enhancements

Using this solution offers numerous benefits. It is flexible, scalable, and performs well. It provides practically infinite levels of nesting in the xml file (barring any call stack limitations when the prototype chain is created). There is also no performance hit from going across a network since the configuration file is local to the app. Among these strengths, there are still improvements that can be made.

Attribute Values

So far, the values of the constants are set as the attribute values in the XML file. Node values could be used as well.

Data Types

Not every value is appropriate as a string. Additional logic could be added to the iteration to have values of appropriate data types (e.g. If the value is meant to be an Integer, make it an Integer; if the value is meant to be a Date, make it a Date).

Caching

This creates an object at runtime. Don’t create the same object every time the app is started. When the object is first created, store it. Then, retrieve it from storage when the app loads again. Only create this object when a change has been made.

Conclusion

This article presented a way to create objects that are easily configurable by updating values in an XML file. As with most things, there are pros and cons to this solution but it does the job, and does the job well. Needless to say, the band is happy and the object has been brought to life.

Thank you for reading and please see my other Creationism articles.

Custom Data-Bound Control for ASP.Net

This post was a result from a question on Code Project asking what the GetData method is. This post will be a basic tutorial on how to create custom data-bound controls for ASP.Net. General knowledge of ASP.Net development with C# will be assumed.

What is GetData()?

The question implies the necessity of a custom data-bound control. When creating a custom data-bound control, the data-binding abilities must be implemented. DataBoundControl, GetData(), DataSourceView, and GetDataSource() are a few methods and classes involved in these custom controls.

DataBoundControl is the base class used to implement custom data-bound controls. It contains methods such as GetData() and GetDataSource() to help with the data-binding implementation of the custom control.

A data-bound control by definition will need to bind to data. There is one important question to answer regarding data: What is the data? Is it a file? Is it a table in a database? If it is a file, what format is it in: CSV, XML, text, pdf? Is it a collection of related data or a single piece? Knowing what the raw data is; its structure; its format; is essential to be able to use it as the underlying data for the data source of the custom control.

A data-bound control will need a data source. The data source is generally set by the user of the control. The data source can be such things as files and database entities as previously implied. When working with binding in the custom control the data is accessed by calling GetData(). The GetData method calls GetDataSource() internally. Calling these methods retrieves an IDataSource instance that is cached by the DataBoundControl object. This instance will remain until the OnDataPropertyChanged method signals that the data source has changed.

Specifically, GetData() returns a DataSourceView. The DataSourceView is a base class and is used by the control for data operations. Creating a custom data-bound control may involve creating a custom DataSourceView. A DataSourceView provides create, read, update, and delete (CRUD) operations for working with the underlying raw data. The corresponding methods are: Insert, Select, Update, and Delete.

In a way, the DataSourceView provides the structure of the data for the data-bound control. Therefore, there are three representations of the raw-data: the raw-data structure itself (XML, database table), the DataSourceView (the structure to provide to the control), and the data-bound control (the way the control presents the data to the user).

That’s the theory. Here’s an example.

The following will be a walkthrough in creating a custom list control. The CustomList control will be created that renders CustomListRecord children controls which will also be demonstrated. First, the CustomListRecord will be shown, then the CustonList control. The process will include setting up necessary Bindable properties, data-binding methods, and rendering.

CustomListRecord : WebControl

The CustomListRecord will contain the text to display to the user. It will be wrapped in a <div> tag and will be attributed with a class named “customlistrecord-data”. The only Bindable property is Text which will be the text displayed to the user. Here is the implementation:

[DefaultProperty("Text")]
[ToolboxData("<{0}:CustomListRecord runat=server></{0}:CustomListRecord>")]
public class CustomListRecord : WebControl
{
   [Bindable(true)]
   [Category("Appearance")]
   [DefaultValue("")]
   [Localizable(true)]
   public string Text
   {
      get
      {
         string s = (ViewState["Text"] as string);
         return ((s == null) ? String.Empty : s);
      }
      set
      {
         ViewState["Text"] = value;
      }
   }

   protected override void RenderContents(HtmlTextWriter output)
   {
      output.WriteBeginTag("div");
      output.WriteAttribute("class", "customlistrecord-data");
      output.Write(">");
      output.WriteEncodedText(this.Text);
      output.WriteEndTag("div");
   }
}

Here we have a class derived from WebControl that has the DefaultPropertyAttribute and ToolboxData attribute. This class has a single property called Text. It is the property used to display text to the user. It has the BindableAttribute, CategoryAttribute, DefaultValueAttribute, and LocalizableAttribute. Click the links for each of the attributes to learn more about them. The property’s backing store is the control’s ViewState. When this control is rendered, it will use the given HtmlTextWriter to emit a <div> tag using the various Write methods. The html will generally look like:

<div class=’customlistrecord-data’> Text to display to the user. </div>

It is very important to emit the “>” character after calls to WriteBeginTag. Otherwise, the opening tag will not be closed properly. The end tags do not need this character.

CustomList : DataBoundControl

Now that the record for the list is created, the creation of the CustomList can begin. Below is the implementation:

[DefaultProperty("Text")]
[ToolboxData("<{0}:CustomList runat=server></{0}:CustomList>")]
public class CustomList : DataBoundControl
{
   public CustomList() : base()
   {
      this._records = new Collection<CustomListRecord>();
   }

   protected override void PerformSelect()
   {
      if (!this.IsBoundUsingDataSourceID)
      {
         this.OnDataBinding(EventArgs.Empty);
      }

      var view = this.GetData();
      view.Select(CreateDataSourceSelectArguments(),
         new DataSourceViewSelectCallback((IEnumerable retrievedData) =>
         {
            if (this.IsBoundUsingDataSourceID)
            {
               this.OnDataBinding(EventArgs.Empty);
            }

            this.PerformDataBinding(retrievedData);
         })
      );
   }

     protected override void PerformDataBinding(IEnumerable data)
     {
           base.PerformDataBinding(data);
           if (data != null)
           {
                 foreach (object dataItem in data)
                 {
                       var record = new CustomListRecord();
                       if (this.DataMember.Length > 0)
                       {
                             record.Text = DataBinder.GetPropertyValue(dataItem, this.DataMember, null);
                       }
                       else
                       {
                             var props = TypeDescriptor.GetProperties(dataItem);
                             if (props.Count > 0)
                             {
                                   for (var i = 0; i < props.Count; i++)
                                   {
                                         var value = props[0].GetValue(dataItem);
                                         if (value != null)
                                         {
                                               record.Text += value.ToString();
                                         }
                                   }
                             }
                             else
                             {
                                   record.Text = String.Empty;
                             }
                       }
                       this._records.Add(record);
                 }

           }

           this.RequiresDataBinding = false;
           this.MarkAsDataBound();
           this.OnDataBound(EventArgs.Empty);
     }

     private IList _records;
     public IList Records
     {
           get
           {
                 if (null == this._records)
                 {
                       this._records = new Collection<CustomListRecord>();
                 }
                 return this._records;
           }
     }

     [Bindable(true)]
     [Category("Appearance")]
     [DefaultValue("")]
     [Localizable(true)]
     public string Title
     {
           get
           {
                 string s = ViewState["Title"] as string;
                 return ((s == null) ? String.Empty : s);
           }
           set
           {
                 ViewState["Title"] = value;
                 if (this.Initialized)
                 {
                       this.OnDataPropertyChanged();
                 }
           }
     }

     protected override void Render(HtmlTextWriter output)
     {
           if (output == null)
           {
                 return;
           }
           if (this._records.Count <= 0)
           {
                 return;
           }
           if (this.Page != null)
           {
                 this.Page.VerifyRenderingInServerForm(this);
           }

           /*
            * <div class="customlist-container">
            *    </div class="customlist-header">
            *       Heading Text
            *    </div>
            *    <div class="customlist-data">
            *       <div class="customlist-record">
            *          <customlistrecord />
            *       </div>
            *       <div class="customlist-record">
            *          <customlistrecord />
            *       </div>
            *    </div>
            * </div>
            */

           output.WriteBeginTag("div");
           output.WriteAttribute("class", "customlist-container");
           output.Write(">");

           output.WriteBeginTag("div");
           output.WriteAttribute("class", "customlist-header");
           output.Write(">");
           output.WriteEncodedText(this.Title);
           output.WriteEndTag("div");

           output.WriteBeginTag("div");
           output.WriteAttribute("class", "customlist-data");
           output.Write(">");

           foreach (CustomListRecord item in this._records)
           {
                 output.WriteBeginTag("div");
                 output.WriteAttribute("class", "customlist-record");
                 output.Write(">");

                 item.RenderControl(output);

                 output.WriteEndTag("div");
           }

           output.WriteEndTag("div");
           output.WriteEndTag("div");
     }
}

CustomList’s Implementation Explained

Here we have a class derived from DataBoundControl that has the DefaultPropertyAttribute and ToolboxData attribute. Each section will be explained.

The Constructor

The constructor simply initializes the _records field with a Collection of CustomListRecords:

public CustomList() : base()
{
   this._records = new Collection<CustomListRecord>();
}

The Properties

This class has two properties: Records and Title.

private IList _records;
public IList Records
{
   get
   {
      if (null == this._records)
      {
         this._records = new Collection<CustomListRecord>();
      }
      return this._records;
   }
}

[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Title
{
   get
   {
      string s = ViewState["Title"] as string;
      return ((s == null) ? String.Empty : s);
   }

   set
   {
      ViewState["Title"] = value;
      if (this.Initialized)
      {
         this.OnDataPropertyChanged();
      }
   }
}

The Title property is used to display the title of the list to the user. It has the BindableAttribute, CategoryAttribute, DefaultValueAttribute, and LocalizableAttribute. The property’s backing store is the control’s ViewState. When this is rendered a <div> tag will be emitted:
<div class=’customlist-header’> Title of the CustomList control </div>
The Records property contains the children CustomListRecord controls. The backing store is the private IList _records field. CustomListRecord controls will be added to this list upon data-binding.

The Data

The PerformSelect method is where the control obtains its data:

protected override void PerformSelect()
{
   if (!this.IsBoundUsingDataSourceID)
   {
      this.OnDataBinding(EventArgs.Empty);
   }

   var view = this.GetData();
   view.Select(CreateDataSourceSelectArguments(),
      new DataSourceViewSelectCallback((IEnumerable retrievedData) =>
      {
         if (this.IsBoundUsingDataSourceID)
         {
            this.OnDataBinding(EventArgs.Empty);
         }
         this.PerformDataBinding(retrievedData);
      })
   );
}

The internals of the PerformSelect method depends on the DataSourceView that is obtained by the call to GetData(). The Select method of the DataSourceView instance is called with DataSourceSelectArguments and a new instance of the DataSourceViewSelectCallback. The Select method, as described by Microsoft’s documentation, asynchronously retrieves a list of data from the underlying data store.

The Binding

Within the DataSourceViewSelectCallback handler is where the binding part of data-binding resides. The binding code is executed in the PerformDataBinding method:

protected override void PerformDataBinding(IEnumerable data)
{
   base.PerformDataBinding(data);

   if (data != null)
   {
      foreach (object dataItem in data)
      {
         var record = new CustomListRecord();

         if (this.DataMember.Length > 0)
         {
            record.Text = DataBinder.GetPropertyValue(dataItem,
               this.DataMember, null);
         }
         else
         {
            var props = TypeDescriptor.GetProperties(dataItem);

            if (props.Count > 0)
            {
               for (var i = 0; i < props.Count; i++)
               {
                  var value = props[0].GetValue(dataItem);
                  if (value != null)
                  {
                     record.Text += value.ToString();
                  }
               }
            }
            else
            {
               record.Text = String.Empty;
            }
         }
         this._records.Add(record);
      }

   }

   this.RequiresDataBinding = false;
   this.MarkAsDataBound();
   this.OnDataBound(EventArgs.Empty);
}

The list below outlines the major aspects of this method:

  • Cycles through the list of data retrieved from the Select method described previously.
  • Upon each item:
    • A new CustomListRecord instance is created
    • An adequate property is found on the data item
    • The property is then assigned to the Text property of the CustomListRecord instance
    • The new CustomListRecord instance is added to the collection of CustomListRecords
  • Notifies listeners that the control has been data-bound.

The Rendering

After data-binding, the control has it’s internals ready for rendering:

protected override void Render(HtmlTextWriter output)
{
        if (output == null)
        {
                 return;
        }

        if (this._records.Count <= 0)
        {
                 return;
        }

        if (this.Page != null)
        {
                 this.Page.VerifyRenderingInServerForm(this);
        }

        /*
         * <div class="customlist-container">
         *    </div class="customlist-header">
         *       Heading Text
         *    </div>
         *    <div class="customlist-data">
         *       <div class="customlist-record">
         *          <customlistrecord />
         *       </div>
         *       <div class="customlist-record">
         *          <customlistrecord />
         *       </div>
         *    </div>
         * </div>
         */

        output.WriteBeginTag("div");
        output.WriteAttribute("class", "customlist-container");
        output.Write(">");

        output.WriteBeginTag("div");
        output.WriteAttribute("class", "customlist-header");
        output.Write(">");
        output.WriteEncodedText(this.Title);
        output.WriteEndTag("div");

        output.WriteBeginTag("div");
        output.WriteAttribute("class", "customlist-data");
        output.Write(">");

        foreach (CustomListRecord item in this._records)
        {
                 output.WriteBeginTag("div");
                 output.WriteAttribute("class", "customlist-record");
                 output.Write(">");

                 item.RenderControl(output);

                 output.WriteEndTag("div");
        }

        output.WriteEndTag("div");

        output.WriteEndTag("div");
}

The DataBoundControl’s Render method is overridden in order to render the data for the user. The first two if-statements help deal with potential invalidity of the control. In this example, nothing is displayed. In a real scenario, it would be wise to add an ability to specify what is done. The comment block in this method merely depicts the html that the code below it will emit. Finally the html is emitted with the control’s Title and Records property. To render each CustomListRecord appropriately, the RenderControl method of the WebControl created earlier is called.

Using the CustomList Control

Now that the CustomList and CustomListRecord control is created, it can be used in an ASP.Net page. The steps provided in the subsequent sections are:

  1. Registering access to the CustomList control at the top of the page.
  2. Adding the CustomList control to the page.
  3. Creating a data source for the CustomList control.
  4. Setting up the data-binding to the data source previously created.
  5. Viewing the results.

Registering Access to the CustomList Control

To use the custom data-bound control, there must be a reference to the Assembly containing it as described in (@ Register):

<%@ Register assembly="DataBoundControls"
      namespace="DataBoundControls.Custom" tagprefix="asp" %>

Please note: Along with the assembly reference on the page, the project the page resides in must also reference the assembly containing the custom data-bound control. If the page and control reside in the same project, the project assembly reference is not necessary.

Adding the CustomList Control

Once the assembly is referenced, the CustomList control can be added to the page:

<body>
        <form id="Form1" runat="server">
               <cc1:CustomList ID="customList" Title="This is the title."
                     runat="server" />
        </form>
</body>

Here the CustomList control is added to the body of the page within a <form> element. The title is set to “CustomList Heading” and runat=”server” is specified.

The page should now generally look like this:

<%@ Page Language="C#" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="AspPageLifeCycle._Default" %>

<%@ Register assembly="ASPNetServerControls"
      namespace="ASPNetServerControls.DataBound" tagprefix="cc1" %>

<html>
<head><title>Custom Data-Bound Controls</title></head>
<body>
        <form id="Form1" runat="server">
               <cc1:CustomList ID="customList" Title="This is the title."
                     runat="server" />
        </form>
</body>
</html>

Creating a Data Source

The CustomList control needs data to bind to. Here, the CustomList’s data source will be created. The data source will consist of a simple List of CustomListDataRecord objects. Here is the implementation of CustomListDataRecord:

public class CustomListDataRecord
{
    public CustomListDataRecord(string text)
    {
        this.Text = text;
    }
    public string Text { get; set; }
}

This object will be used to provide the item data for each CustomListRecord in the CustomList control. The data source will be of type List<CustomListDataRecord>. Here is the code:

var data = new List<CustomListDataRecord>();
data.Add(new CustomListDataRecord("Hello,"));
data.Add(new CustomListDataRecord("world!"));
data.Add(new CustomListDataRecord("This"));
data.Add(new CustomListDataRecord("is goodbye..."));

The above code creates a new List<CustomListDataRecord> instance and adds four items. This list will be used as the data source for the CustomList control on the page. Placement of this code will be described below.

Data-Binding Setup

Next comes the data-binding setup. The steps here include assigning the List<CustomListDataRecord> instance to customList’s DataSource property, using CustomListDataRecord’s Text property for the DataMember, and calling DataBind(). Here is the code that does this:

customList.DataSource = data;
customList.DataMember = "Text";
customList.DataBind();

The above code sets up the data-binding for the CustomList instance and then calls DataBind. The DataBind method will in turn call the methods we created in the CustomList control. The following section will describe the placement of this code.

Viewing the Results

At this point, the CustomList is created, added to the page, and is set up for data-binding. The code in the previous two sections will be placed in the PreRender page event handler:

protected void Page_PreRender(object sender, EventArgs e)
{
        var data = new List<CustomListDataRecord>();
        data.Add(new CustomListDataRecord("Hello,"));
        data.Add(new CustomListDataRecord("world!"));
        data.Add(new CustomListDataRecord("This"));
        data.Add(new CustomListDataRecord("is goodbye..."));

        customList.DataSource = data;
        customList.DataMember = "Text";
        customList.DataBind();
}

Further information on the PreRender event and the ASP.Net Life Cycle can be found here (ASP.Net Page Life Cycle Overview). With this code in place, the project should be ready to run! Run the project to view the created page in the browser. The page shouldn’t look too much different than below:

The view inside the browser

The page doesn’t look like much but, the html provides great potential with CSS.

Conclusion

Custom data-bound controls depend on data, data structures, and rendering. This article described the creation of each of these. There can certainly be improvements to the control ranging from default CSS to more robust data-binding and the inclusion of item templating. The code provided lays a foundation to improve upon.