ASP.NET Developer’s Cookbook, Chapter 13


Chapter 13: Rendering Data with ASP.NET Web Controls

13.0. Introduction

ASP.NET provides several Web controls that make displaying data on a Web page easier than ever before. This chapter shows you how to take advantage of a process called data-binding to easily display data in a variety of formats using very little code. This chapter covers many of the most commonly used features of the Repeater, DataList, and DataGrid, including some fairly advanced DataGrid features. Using these data-bound Web controls, it is very easy to write data-driven Web Forms by just dragging and dropping a few controls onto a form and writing a few lines of code.

13.1. Rendering Data Directly on a Web Form

You want to display a piece of data on a Web Form using data-binding.


You can use the <%#%> syntax to easily bind data to a control. Simply create a variable, assign it a value, and call Page.DataBind to bind it to the page. The ASPX page is as follows:

  <form id="Recipe1401vb" method="post" runat="server">
   <asp:Label ID="MyLabel" Runat="server">Hello <%#FirstName%>!

In <script runat="server" /> block or codebehind:

Protected FirstName as string

Sub Page_Load(sender As Object, e As EventArgs)
End Sub


If you are using codebehind, it is important to declare the variable with Protected access level so the page can access it. It is also important to realize that calling Page.DataBind() will result in all controls on the page being data-bound, because any time a control container calls its DataBind() method, it recursively calls the DataBind() method of all of its child controls.

More by Author

Must Read