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 goodpractice? Is a developer giving up control of their code by using thistechnique? When would it be better to build a control's content (e.g., theitems in a list box) programmatically without using the DataSourceproperty?
- 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 anydata structure that implements either the IEnumerable, ICollection,or IListSource interfaces. Examples of classes that implement one of thenecessary interfaces include ArrayList, Hashtable, DataView,DataReader, and DataSet.
So exactly what is data binding? If you look over anyclassic ASP code that accesses a recordset and enumerates the data to render atable 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 therecordset Fields
For Each objField inobjRS.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 newdata-binding feature:
<Script runat="server">
Public FunctionPage_Load(sender As Object, e As EventArgs)
Dim myConnection AsNew SqlConnection(...connection string...)
Dim myCommand As NewSqlCommand("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 whenusing data binding. The answer: absolutely not. In the previous exampleusing the DataGrid, the columns returned will be used to generatecolumns automatically in the rendered table. If you want more control over howthis is rendered, you can use templates like this:
<Script runat="server">
Public FunctionPage_Load(sender As Object, e As EventArgs)
Dim myConnection AsNew SqlConnection(...connection string...)
Dim myCommand As NewSqlCommand("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 DataListand specified a template, in this case the ItemTemplate. When databinding 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 DataListsupport. Additional templates include HeaderTemplate, AlternatingItemTemplate,SeparatorTemplate, and FooterTemplate.
In the pre-.NET era, it was very popular to build sitesusing an XML-XSL combination: XML for the content, and XSL for the structureand graphics. How can you accomplish this in ASP.NET? The Web controls createthe HTML automatically and they bind the data on the server side, so the HTMLcomes to the browser with the data in it. Does this mean the XML-XSL technologyis no longer relevant and should be used only for data exchange betweenapplications?
- Memi Lavi
What Memi refers to is a design pattern for buildingapplications that lets you control the mark-up sent to a client requesting aWeb application. All the site content and data is available in a raw XMLformat, instead of being tightly coupled to the mark-up. Then an XSLT templateis applied to the XML based on the client making the request. A great exampleof this is a list of flight times stored in an XML file and then transformed toHTML if the client were a Web browser, or transformed to WML if the requestoriginated from a mobile device. This works nicely because you can render theappropriate content by simply providing the correct XSLT template for transformingthe XML.
ASP.NET supports this transformation scenario with the XMLserver control. In Here, the XSL transforms the XML on the server and rendersthe content to the client:
<%@ Page Language="vb"AutoEventWireup="false"
Codebehind="XmlControl1.aspx.vb"
Inherits="TipsTricks.XmlControl1"%>
<HTML>
<body>
<asp:xmlid="MyXml1"
DocumentSource="SalesData.xml"
TransformSource="SalesChart.xsl"
runat="server" />
</body>
</HTML>
I wouldn't go as far to say that XML-XSL technology is nolonger relevant; however, ASP.NET does make a lot of what XML/XSLT does easierthrough server controls. ASP.NET server controls provide declarative,encapsulated application functionality and are capable of rendering differentcontent for different devices - if the server control supports the device. Agreat example of this is the Microsoft Mobile Internet Toolkit (MMIT), whichincludes a suite of server controls that can intelligently render HTML or WMLbased on the device from which the request originated. You can learn more aboutthe 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 Howardis a program manager on the ASP.NET team. He also writes the MicrosoftDeveloper 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 thisarticle to mailto:feedback@aspnetPRO.com.Please include the article title and author.