Ask Microsoft
When Should You Use Data Binding?
Want to know what data binding is and when to use it?
Need to transform XML using ASP.NET? Rob's got the answers.
By Rob Howard
In this installment I'll address a couple great questions,
starting off with when you should use data binding.
Is using the DataSource property of a control to
"bind" to a data source, such as a DataSet or DataTable, a good
practice? Is a developer giving up control of their code by using this
technique? When would it be better to build a control's content (e.g., the
items in a list box) programmatically without using the DataSource
property?
- Michael Hodnick
Several ASP.NET server controls - especially DataGrid,
DataList, Repeater, DropDownList, and ListBox -
support the concept of data binding. Data binding allows you to bind to any
data structure that implements either the IEnumerable, ICollection,
or IListSource interfaces. Examples of classes that implement one of the
necessary interfaces include ArrayList, Hashtable, DataView,
DataReader, and DataSet.
So exactly what is data binding? If you look over any
classic ASP code that accesses a recordset and enumerates the data to render a
table or display a <select>
drop down, you'll recall seeing code that looks similar to this:
<%
Response.Write "<TABLE BORDER=0 CELLSPACING=1>"
' Display table headings for each column in the recordset
Dim objField
Response.Write "<TR>" & vbNewLine
For Each objField in objRS.Fields
Response.Write
"<TH>" & objField.Name & "</TH>" &
_
vbNewLine
Next
Response.Write "</TR>" & vbNewLine
' Now loop through the recordset, displaying TR/TD tags
Do While Not objRS.EOF
' Write the TR
Response.Write
"<TR>" & vbNewLine
' Now loop through the
recordset Fields
For Each objField in
objRS.Fieldsd
Response.Write
"<TD>" & objField.Value & "</TD>" &
_
vbNewLine
Next
' Close the TR tag
Response.Write
"</TR>" & vbNewLine
' Advance the recordset
objRS.MoveNext
Loop
' Close the table tag...
Response.Write "</TABLE>" & vbNewLine
%>
Here's how you generate the same table with ASP.NET's new
data-binding feature:
<Script runat="server">
Public Function
Page_Load(sender As Object, e As EventArgs)
Dim myConnection As
New SqlConnection(...connection string...)
Dim myCommand As New
SqlCommand("SELECT * FROM AUTHORS", myConnection)
myConnection.Open()
myDataGrid.DataSource
= myCommand.ExecuteReader()
myDataGrid.DataBind()
myConnection.Close()
End Function
</Script>
<asp:DataGrid runat="server" id="myDataGrid"/>
I think we can all agree that the latter is much cleaner.
But Michael also asks whether he is sacrificing flexibility or control when
using data binding. The answer: absolutely not. In the previous example
using the DataGrid, the columns returned will be used to generate
columns automatically in the rendered table. If you want more control over how
this is rendered, you can use templates like this:
<Script runat="server">
Public Function
Page_Load(sender As Object, e As EventArgs)
Dim myConnection As
New SqlConnection(...connection string...)
Dim myCommand As New
SqlCommand("SELECT * FROM AUTHORS", myConnection)
myConnection.Open()
myDataList.DataSource
= myCommand.ExecuteReader()
myDataList.DataBind()
myConnection.Close()
End Function
</Script>
<asp:DataList runat="server" id="myDataList">
<ItemTemplate>
<b><%#
DataBinder.Eval(Container.DataItem("fname")) %>
</ItemTemplate>
</asp:DataList>
In the previous sample, I changed the server control to a DataList
and specified a template, in this case the ItemTemplate. When data
binding occurs, the DataList renders each record using this template.
This gives you a high degree of control over the display of the server control.
The ItemTemplate is but one of the templates that the DataList
support. Additional templates include HeaderTemplate, AlternatingItemTemplate,
SeparatorTemplate, and FooterTemplate.
In the pre-.NET era, it was very popular to build sites
using an XML-XSL combination: XML for the content, and XSL for the structure
and graphics. How can you accomplish this in ASP.NET? The Web controls create
the HTML automatically and they bind the data on the server side, so the HTML
comes to the browser with the data in it. Does this mean the XML-XSL technology
is no longer relevant and should be used only for data exchange between
applications?
- Memi Lavi
What Memi refers to is a design pattern for building
applications that lets you control the mark-up sent to a client requesting a
Web application. All the site content and data is available in a raw XML
format, instead of being tightly coupled to the mark-up. Then an XSLT template
is applied to the XML based on the client making the request. A great example
of this is a list of flight times stored in an XML file and then transformed to
HTML if the client were a Web browser, or transformed to WML if the request
originated from a mobile device. This works nicely because you can render the
appropriate content by simply providing the correct XSLT template for transforming
the XML.
ASP.NET supports this transformation scenario with the XML
server control. In Here, the XSL transforms the XML on the server and renders
the content to the client:
<%@ Page Language="vb"
AutoEventWireup="false"
Codebehind="XmlControl1.aspx.vb"
Inherits="TipsTricks.XmlControl1"%>
<HTML>
<body>
<asp:xml
id="MyXml1"
DocumentSource="SalesData.xml"
TransformSource="SalesChart.xsl"
runat="server" />
</body>
</HTML>
I wouldn't go as far to say that XML-XSL technology is no
longer relevant; however, ASP.NET does make a lot of what XML/XSLT does easier
through server controls. ASP.NET server controls provide declarative,
encapsulated application functionality and are capable of rendering different
content for different devices - if the server control supports the device. A
great example of this is the Microsoft Mobile Internet Toolkit (MMIT), which
includes a suite of server controls that can intelligently render HTML or WML
based on the device from which the request originated. You can learn more about
the MMIT at http://www.asp.net/.
If you want to learn more about ASP.NET or have questions,
check out the ASP.NET Forums at http://www.asp.net
(look for the Forums tab), or send e-mail to mailto:AskMicrosoft@aspnetPRO.com.
Rob Howard
is a program manager on the ASP.NET team. He also writes the Microsoft
Developer Network's "Nothing but ASP.NET" column and is a co-author of Professional ASP.NET
(Wrox Press).
Tell us what you think! Please send any comments about this
article to mailto:feedback@aspnetPRO.com.
Please include the article title and author.