[ASP.NET] Data-Bound Server Controls

Once you have data, regardless of the origin, you are ready to display them for users. ASP.NET provides server controls, which are specially designed to bind data and display them in a specific format. These data-bound controls are highly configurable with almost no programming code.   

 

1. Simple Data-bound Controls

The simple data-bound controls are used to display key-value dictionary style data on a web page. They inherit from the “System.Web.UI.WebControls.ListControl“.

  • DropDownList
  • ListBox
  • CheckBoxList
  • RadioButtonList
  • BulletedList
public abstract class ListControl : DataBoundControl
{
  public string DataTextField { get; set; }
  public string DataValueField { get; set; }
  public string DataTextFormatString { get; set; }

  public int SelectedIndex { get; set; }
  public ListItem SelectedItem { get; }
  public string SelectedValue { get; set; }
}

The “Items” property holds a collection of “ListItem” objects.

public sealed class ListItem
{
  public string Text { get; set; } // displays for users
  public string Value { get; set; } // posts back to the server
}
  • When the data binding is used, you can set “Text” and “Value” of each item using “DataTextField” and “DataValueField” properties
  • To check which item is selected, Use “SelectedIndex“, “SelectedItem“, or “SelectedValue” property

– ListBox –

public class ListBox : ListControl
{
  public ListSelectionMode SelectionMode { get; set; } // Single (default), Multiple
  public int Rows { get; set; }
}

– CheckBoxList and RadioButtonList –

public class CheckBoxList : ListControl
{
  protected int RepeatedItemCount { get; } // the number of list items
  public int RepeatColumns { get; set; } // default is 0
  public RepeatDirection RepeatDirection { get; set; } // Horizontal, Vertical (default)
  public virtual RepeatLayout RepeatLayout { get; set; } // Table (default), Flow, UnorderedList, OrderedList
}

public class RadioButtonList : ListControl
{
  protected int RepeatedItemCount { get; } // the number of list items
  public int RepeatColumns { get; set; } // default is 0
  public RepeatDirection RepeatDirection { get; set; } // Horizontal, Vertical (default)
  public RepeatLayout RepeatLayout { get; set; } // Table (default), Flow, UnorderedList, OrderedList
}

– BulletedList –

public class BulletedList : ListControl
{
  public BulletedListDisplayMode DisplayMode { get; set; } // Text (default), LinkButton(“Click” event fires), or HyperLink(navigate to the url)

  public BulletStyle BulletStyle { get; set; } // Disc, Circle, or Square; Numbered, LowerAlpha, UpperAplha, LowerRoman or UpperRoman; CustomImage or NotSet (default)
  public string BulletImageUrl { get; set; }
  public int FirstBulletNumber { get; set; }
}

– Events –

public class ListControl
{
  public event EventHandler SelectedIndexChanged;
}

public class BulletedList : ListControl
{
  public event BulletedListEventHandler Click;  // with LinkButton DisplayMode
}
<asp:ListBox ID="productCategoryLB" runat="server" AutoPostBack="True"
  DataSourceID="productCategorySqlDS"
  DataTextField="Name"
  DataValueField="ProductCategoryID">
<br /><br />
<asp:BulletedList ID="productSubCategoryBL" runat="server"
 DataSourceID="productSubCategorySqlDS"
 DataTextField="Name"
 DataValueField="ProductSubcategoryID" BulletStyle="Circle">
</asp:BulletedList>

<asp:SqlDataSource ID="productCategorySqlDS" runat="server"
 ConnectionString="ConnectionStrings</span>:AdventureWorks %>"
 SelectCommand="SELECT [ProductCategoryID], [Name] FROM [Production].[ProductCategory]">

<asp:SqlDataSource ID="productSubCategorySqlDS" runat="server"
 ConnectionString="ConnectionStrings</span>:AdventureWorks %>"
 SelectCommand="SELECT [ProductSubcategoryID], [Name] FROM [Production].[ProductSubcategory] WHERE ([ProductCategoryID] = @ProductCategoryID)">
 <SelectParameters>
   <asp:ControlParameter ControlID="productCategoryLB" Name="ProductCategoryID" PropertyName="SelectedValue" Type="Int32" />
 </SelectParameters>
</asp:SqlDataSource>

 

2. Composite data-bound controls

The power of data binding really shines when you can bind table data to server controls.  Controls that inherit from the “CompositeDataBoundControl” class provide more advanced data binding functionalities.

  • Table style + Templates: GridView and DetailsView
  • Templates: FormView, Repeater, ListView, and DataList

The rich data controls are:

  • GridView: all-purpose grid control but heavyweight
  • DetailsView: ideal for showing a single record at a time with the ability to move back and forth
  • FormView: displaying a single record with the support of editing, based on templates
  • Repeater: displaying multiple rows, based on the read-only template (no EditTemplate)
  • ListView: displaying multiple rows like a Repeater but supports many additional templates such as LayouTemplate, ItemSeparatorTemplate, and GroupTemplate (Repeater is replaced by ListView)
<asp:GridView ID="productGridView" runat="server" DataSourceID="productSqlDS">
</asp:GridView>

<asp:SqlDataSource ID="productSqlDS" runat="server"
  ConnectionString="ConnectionStrings:AdventureWorks %>"
  SelectCommand="SELECT [DepartmentID], [Name], [GroupName] FROM [HumanResources].[Department]">
</asp:SqlDataSource>

 

3. Data Binding

All data binding controls are derived from the “BaseDataBoundControl” class. They bind data to them using “DataBind()” method and will raise “DataBound” event.

– BaseDataBoundControl –

public abstract class BaseDataBoundControl : WebControl
{
  public Object DataSource { get; set; }
  public string DataSourceID { get; set; }
}

Data objects should implement  IEnumerable, IListSource, IDataSource, or IHierarchicalDataSource interfaces.

 

4. Templates

Some of the rich data bound controls use templates for maximum flexibility. You can define several templates for a single control.

  • HeaderTemplate: optional header
  • FooterTemplate: optional footer
  • ItemTemplate: is rendered for each row in the data source
  • AlternatingItemTemplate: optional, if defined, every other row is rendered using this template
  • SelectedItemTemplate: optional, used for a selected row
  • SeparatorTemplate: optional, defines the separation of each item and alternate item
  • EditItemTemplate: optional, used for a row in edit mode

 

5. Formatting Fields

When you use rich data bound controls, you are forced to bind data to a cell (GridView) or a control in a template. It is crucial to understand how you can  fine-tune the textual display of a field value. It is especially useful for numbers, dates and currencies.

– Numbers –

  • {0:C}: currency – locale specific format
  • {0:E}: scientific – 1.2E+03
  • {0:P}: percentage – 56.4%
  • {0:Fx}: fixed decimal – {0:F3} 123.456,  {0:F0} 123

– Date / Time –

  • {0:d}: short date – 10/24/2011
  • {0:D}: long date –  Monday, October 24, 2011
  • {0:f}: long date and short time: Monday, October 24, 2011 9:00 AM
  • {0:F}: long date and long time: Monday, October 24, 2011 9:00:10 AM
  • {0:M}: month and day – October 24
  • {0:G}: general, depending on the locale – 10/24/2011 2011 9:00:10 AM
  • custom such as {0:MM/dd/yy} or {0:MM/dd/yyyy}

 

6. DataBinder class

When you use templates, you need to bind data to controls. How can you do that? Simple binding expressions are not enough because  you are not dealing with the specific value yet. Mostly you are creating a template for a column.

The “System.Web.UI.DataBinder” class’s static method “Eval()” will solve the problem.

  • Eval(): uses Reflection to perform a lookup of a underlying data type, one-way (read-only) binding
public sealed class DataBinder
{
  public static Object Eval(Object container, string expression);
  public static string Eval(Object container, string expression, string format);
}

For two-way bindings, “Bind()” is used. Strictly speaking, “Bind()” is not a method. It is a special notation for two-way binding. ASP.NET designers want it to look like “Eval()”

  • Bind(): two-way binding, can be used for insert and edit scenarios
<%# Bind(“Price”, “{0:C}”) %>
<%# Eval(“FirstName”) %>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s