Developer

Gain power and flexibility with data binding in .NET

Tony Patton believes that developers should add data binding to their development toolbox. In this article, he explains what data binding is and demonstrates how you can bind data to various structures within .NET.

I once discussed data binding with a junior developer who wanted to display text in a Repeater control but didn't have a database connection to use as its data source. I pointed out that he could utilize data binding within the .NET Framework.

Data binding provides enormous power and flexibility when developing .NET applications. Learn what data binding is and how you can bind data to various structures within .NET.

Data binding defined

Data binding is binding controls to data, which may originate in a relational database or another data structure. Data binding allows you to bind a control to a specific column from a database table or element within a data structure. Basically, data binding provides a simple, convenient, and powerful way to create a link between a control and application data.

I'll concentrate on ASP.NET controls in this article. ASP.NET provides various data controls that may utilize data binding. These controls include (but aren't limited to) the following:

  • DropDownList
  • ListBox
  • DataGrid
  • DataList
  • Repeater
  • CheckBoxList
  • RadioButtonList

Binding a control to a database resultset

The following C# code is in the codebehind file for your sample ASP.NET page. It issues a simple command to a MySQL database server. The command (SHOW DATABASE) retrieves a list of available databases. Note: The MySQL Connector/Net 1.0 is used to connect to MySQL. It's referenced in the code by the following using statement:

using MySql.Data.MySqlClient;

Here's the Page_Load portion of the codebehind file:

protected System.Web.UI.WebControls.Repeater Repeater1;
void Page_Load(object sender, System.EventArgs e) {
string connStr = "server=localhost; database=sitepoint; pooling=false";
MySqlConnection conn = null;
MySqlDataReader reader = null;
MySqlCommand cmd = null;
try {
conn = new MySqlConnection( connStr );
conn.Open();
cmd = new MySqlCommand("SHOW DATABASES", conn);
reader = cmd.ExecuteReader();
Repeater1.DataSource = reader;
Repeater1.DataBind();
} catch (MySqlException ex)  {
Response.Write("MySQL Exception: " + ex.Message);
}  catch (Exception ex) {
Response.Write("Exception: " + ex.Message);
} finally     {
if (reader != null) reader.Close();
if (conn != null) conn.Close();
} }

The corresponding ASP.NET Web Form contains a Repeater control. Notice that this control is tied to your database query by assigning the Repeater's DataSource property to the result set (MySqlDataReader object). The data bind is enforced with a call to the Repeater's DataBind method. All of the controls contain the DataSource property and the DataBind method.

The corresponding ASP.NET source is below:

<%@ Page language="c#" Codebehind="BuilderSample2.aspx.cs"
AutoEventWireup="false" Inherits="BuilderDataBindingCSharp.BuilderSample2" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html><head><title>Builder Sample</title></head>
<body>
<form id="frmBuilderSample" method="post" runat="server">
<table>
<asp:Repeater id="Repeater1" runat="server">
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem, "Database") %></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</form></body></html>

The Repeater control is contained in an HTML table for formatting. The DataBinder.Eval statement retrieves the specified column value from the data source tied to the control. In this instance, the Database column is returned. Notice that the result of the SHOW DATABASE returns values assigned to the name Database.

Let's take the concept further by binding different data structures.

Binding controls to other data structures

The wonderful thing about data binding is that you aren't restricted to data from a database call. You can create and populate your own custom data structures, or you can use ones in the .NET Framework. This includes ArrayList, Hashtable, and regular arrays.

For example, you may want to create an array of custom object types and bind it to a control. The next example binds an ArrayList object (from the System.Collections namespace) containing custom object types (Person) to a Repeater control. The Person class is included with the code for brevity, but it would most likely exist in its own class file in a production environment.

<%@ Page language="c#" %>
<%@ Import Namespace="System.Collections" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<script language="C#" runat="server">
public class Person {
public Person() { }
private string firstName;
private string lastName;
public string FirstName {
get {
return this.firstName;
}
set {
this.firstName = value;
} }
public string LastName {
get {
return this.lastName;
}
set {
this.lastName = value;
} } }
private void Page_Load(object sender, System.EventArgs e) {
ArrayList alTest = new ArrayList(3);
Person p1 = new Person();
p1.FirstName = "Lenny";
p1.LastName = "Dykstra";
alTest.Add(p1);
Person p2 = new Person();
p2.FirstName = "John";
p2.LastName = "Kruk";
alTest.Add(p2);
rptPeople.DataSource = alTest;
rptPeople.DataBind();
}
</script>
<html><head><title>WebForm1</title></head>
<body>
<form id="frmBuilderSample" method="post" runat="server">
<asp:Repeater id="rptPeople" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "LastName") %>,
<%# DataBinder.Eval(Container.DataItem, "FirstName") %>
<br />
</ItemTemplate>
</asp:Repeater>
</form></body></html>

Notice that the code creates two instances of the People class and adds them to the ArrayList object. The property names from the Person class are used to assign column names (DataBinder.Eval statement) to the Repeater control within the ASP.NET source. A normal array object works in the same manner.

The VB.NET equivalent follows (notice that fName and lName are used in place of firstName and lastName since VB.NET isn't case-sensitive):

<%@ Page language="vb" %>
<%@ Import Namespace="System.Collections" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<script language="vb" runat="server">
Public Class Person
Private fName As String
Private lName As String
Public Property FirstName As String
Get
return Me.fName
End Get
Set
Me.fName = value
End Set
End Property
Public Property LastName As String
Get
return Me.lName
End Get
Set
Me.lName = value
End Set
End Property
End Class
Sub Page_Load
Dim alTest As ArrayList
Dim p1 As New Person()
alTest = New ArrayList(3)
p1.FirstName = "Lenny"
p1.LastName = "Dykstra"
alTest.Add(p1)
Dim p2 As New Person()
p2.FirstName = "John"
p2.LastName = "Kruk"
alTest.Add(p2)
rptPeople.DataSource = alTest
rptPeople.DataBind()
End Sub
</script>
<html><head><title>WebForm1</title></head>
<body>
<form id="frmBuilderSample" method="post" runat="server">
<asp:Repeater id="rptPeople" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "LastName") %>,
<%# DataBinder.Eval(Container.DataItem, "FirstName") %>
<br />
</ItemTemplate>
</asp:Repeater>
</form></body></html>

Another option is the Hashtable object located in the System.Collections namespace. A Hashtable represents a collection of key-and-value pairs organized by the hash code of the key. The Hashtable's Add method is used to add items to it, with the first parameter being the key and the second containing the associated value.

When using a Hashtable for data binding, you should use Key and Value to assign elements to a control via the DataBinder.Eval statement. The following ASP.NET source shows this in action using C#:

<%@ Page language="c#" %>
<%@ Import Namespace="System.Collections" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e) {
Hashtable ht = new Hashtable(3);
ht.Add("Development", "Builder.com");
ht.Add("News", "News.com");
ht.Add("Technology", "TechRepublic.com");
rptPeople.DataSource = ht;
rptPeople.DataBind();
}
</script>
<html>
<head><title>Bind with Hashtable</title>    </head>
<body>
<form id="frmBuilderSample" method="post" runat="server">
<h1>Notable Web Sites</h1>
<table cellpadding="5" border="1">
<asp:Repeater id="rptPeople" runat="server">
<ItemTemplate>
<tr><td><%# DataBinder.Eval(Container.DataItem, "Key") %></td>
<td><%# DataBinder.Eval(Container.DataItem, "Value") %></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table></form></body></html>

The equivalent VB.NET code follows:

<%@ Page language="vb" %>
<%@ Import Namespace="System.Collections" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<script language="vb" runat="server">
Sub Page_Load
Dim ht As Hashtable
ht = New Hashtable
ht.Add("Development", "Builder.com")
ht.Add("News", "News.com")
ht.Add("Technology", "TechRepublic.com")
rptPeople.DataSource = ht
rptPeople.DataBind()        
End Sub
</script>
<html>
<head><title>Bind with Hashtable</title>    </head>
<body>
<form id="frmBuilderSample" method="post" runat="server">
<h1>Notable Web Sites</h1>
<table cellpadding="5" border="1">
<asp:Repeater id="rptPeople" runat="server">
<ItemTemplate>
<tr><td><%# DataBinder.Eval(Container.DataItem, "Key") %></td>
<td><%# DataBinder.Eval(Container.DataItem, "Value") %></td>
</tr></ItemTemplate></asp:Repeater>
</table></form></body></html>

Though I've focused on the Repeater control, a Hashtable would work as well as any other control. The following sample demonstrates this with the Hashtable's key used as the value behind the ListBox control:

<%@ Page language="c#" %>
<%@ Import Namespace="System.Collections" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e) {
Hashtable ht = new Hashtable(3);
ht.Add("Development", "Builder.com");
ht.Add("News", "News.com");
ht.Add("Technology", "TechRepublic.com");
lstStatus.DataSource = ht;
lstStatus.DataTextField = "Value";
lstStatus.DataValueField = "Key";
lstStatus.DataBind();
}
</script>
<html><head><title>ListBox HashTable Example</title></head>
<body>
<form id="frmBuilderSample" method="post" runat="server">
<asp:ListBox id="lstStatus" runat="server" />
</form></body></html>

The VB.NET equivalent follows:

<%@ Page language="vb" %>
<%@ Import Namespace="System.Collections" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<script language="VB" runat="server">
Sub Page_Load
Dim ht As Hashtable
ht = New Hashtable(3)
ht.Add("Development", "Builder.com")
ht.Add("News", "News.com")
ht.Add("Technology", "TechRepublic.com")
lstStatus.DataSource = ht
lstStatus.DataTextField = "Value"
lstStatus.DataValueField = "Key"
lstStatus.DataBind()
End Sub
</script>
<html><head><title>ListBox HashTable Example</title></head>
<body>
<form id="frmBuilderSample" method="post" runat="server">
<asp:ListBox id="lstStatus" runat="server" />
</form>    </body></html>

These examples demonstrate the use of arrays and a Hashtable object to bind data to a control. After witnessing the benefits of data binding, I hope you'll add it to your development toolbox.

TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically sign up today!

About Tony Patton

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

Editor's Picks

Free Newsletters, In your Inbox