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 with a “customlistrecord-data” class attribute. 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</span> 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" %>

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 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 <a title=”List” href=”http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx” target=”_blank” rel=”noopener noreferrer”>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. 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 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 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.