Learning ASP.NET for the ASP Developer, Part 1
Pages: 1, 2
Technically speaking, in ASP.NET we set the source of the data of this tag (referred to
as the DataSource) to the records that were pulled from the database. (The
records themselves are pulled into a table, which can be accessed as a whole by referring
to the DefaultView of the zeroth table, Table(0), as RecordSet.Table(0).DefaultView.) Once
we have set the DataSource for all relevant tags, we next tell ASP.NET to actually
start the population process to write the appropriate HTML for displaying the
multiple records using a method for binding the data or recordset to
the datagrid. This binding operation is known as the DataBind method.
This process can be summarized in four steps:
-
Define
<asp:datagrid> ... </asp:datagrid>in the presentation block and assign it an ID. - Extract the relevant records from the database.
-
Set the
DataSourceof theDataGridto the records extracted. -
Use the
DataBindmethod to populate the grid with the appropriate HTML (each record is displayed as a row in the table, and each field as a table column).
To fix ideas, we first consider the same HTML table to display our books that is devoid of any special layout--a plain vanilla table. The table is bare-bones but allows you to see the essential program flow. The following is a complete code listing; however, for now, please focus on the highlighted code in the script block. (We'll discuss the rest of the code structure in the subsequent part of this series.)
<%@ Page Language="vb" Debug="True" Trace="True" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<script runat="server">
'System.Web.UI.Controls namespace for the DataGrid control
'System.Data namespace for the Dataset class
'System.Data.SqlClient namespace for SQL server classes
Sub Page_Load()
'Set up the SQL Server database connection
Dim ConnStr As String = "server='(local)'; trusted_connection=true; database='Demo'"
Dim RecordSet As DataSet
RecordSet = new DataSet()
'Now, pull the records from the database
Dim SQL As String = "Select * from Books"
Dim RecordSetAdpt As new SqlDataAdapter(SQL, ConnStr)
RecordSetAdpt.Fill(RecordSet)
'Set the data grid's source of data to this recordset
DataGrid1.DataSource = RecordSet.Tables(0).DefaultView
'Finally, bind this data to the control
DataGrid1.DataBind()
End Sub ' end of Page_Load
</script>
<!-- -------------Presentation/Markup Block Below -------------------------------- -->
<html>
<head>
</head>
<body>
<form runat="server">
<asp:DataGrid id="DataGrid1" runat="server">
</asp:DataGrid>
</form>
</body>
</html>
You will notice right away that the entire code seems to be eerily lacking in HTML tags. This lack of pure HTML is typical of ASP.NET pages; very often you will find yourself with pages that have barely any HTML, yet display rich content.
Finally, the following graphic makes a side-by-side comparison of classic ASP code versus ASP.NET code. The graphic shows the similarity of ASP.NET and classic ASP, as well the differences. Specifically, it illustrates how ASP.NET is better able to keep presentation separate from script than classic ASP.
Improving Table Presentation
While the simple table being discussed so far is fine for introducing ASP.NET, the
tables that we are likely to encounter in practice are going to have more formatting.
So, now, let's add some color to the table headers to demonstrate how we can still
add markup attributes to presentational elements yet maintain the separation
of server-side-script code from the presentation elements. More specifically,
notice that the headers in the vanilla table are simply the names of the corresponding
fields in the database. But the field names may not always be in the form we'd
like to display on a web page. So, this time, we will define a table in which we will
change the heading of the Title field to a more descriptive one, Title of Book.
Since the data records that appear in the table do not change--the changes we want
to make are purely for display--we can expect to make all of our modifications in
the presentation block with absolutely no changes in the server-side-script block.
All specifications will be made within the <asp:DataGrid> ... </asp:DataGrid> tags,
as shown below:
<asp:DataGrid id="DataGrid1" runat="server">
<!-- Presentation Specification -->
</asp:DataGrid>
First, we'll describe how to specify background colors for the table headers. Table
headers, footers, and presentational elements can be specified using <HeaderStyle>
... </HeaderStyle>, <FooterStyle> ... </FooterStyle>, and <ItemStyle>
... </ItemStyle>, respectively. (Note that all tags are case-sensitive.)
On each style element tag, specify the forecolor and backcolor attributes. In
the following snippet, we specify the table headers:
<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False">
<HeaderStyle forecolor="White" backcolor="#006699"></HeaderStyle>
</asp:DataGrid>
The datagrid element automatically builds a plain table. So if we want to modify
the default column titles, we need to suppress the defaults. This suppression
is accomplished by setting the AutoGenerateColumns attribute on the DataGrid element
to False. Once we suppress the automatic generation of the columns, we then specify
the column presentation information within the <columns> ... </columns>
tags within the DataGrid tags.
<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False">
<HeaderStyle forecolor="White" backcolor="#006699"></HeaderStyle>
<Columns>
<!-- Columns Specification -->
</Columns>
</asp:DataGrid>
Each column can be independently controlled using the <asp:BoundColumn>
... </asp:BoundColumn> tags. The name of this tag is not as unusual as
it first looks. Recall that the data that is extracted from the database is bound
to the DataGrid using the DataBind( ) method. Thus, the BoundColumn refers
to a column that is bound to a specific field in a database table. Specifically, we can control the titles that
appear on the header columns. The DataField attribute specifies the database field
that the table column is associated with, and the HeaderText attribute specifies
the title that appears in the header for this column. (While we haven't shown it
in this example, you can also specify styles individually for each column within the <asp:BoundColumn>
... </asp:BoundColumn> tags, thus giving you complete flexibility
in the presentation of a table. In addition, we can also modify the order of
the columns by rearranging the order of the <asp:BoundColumn> ... </asp:BoundColumn> tags
for each column within the <Columns> ... </Columns> tags.) Here
is the code listing for our Books example, in which we do not show the ID column
and display the price before the book's title:
<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False">
<HeaderStyle forecolor="White" backcolor="#006699"></HeaderStyle>
<Columns>
<asp:BoundColumn DataField="Price ($)" HeaderText="Price (US$)">
<ItemStyle horizontalalign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="Title" HeaderText="Book Title">
<ItemStyle horizontalalign="Left"></ItemStyle>
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
This code produces the following table when viewed in a browser:
| Price (US$) | Book Title |
| 45 | ASP.NET in a Nutshell |
| 40 | ASP.NET Cookbook |
While the specification for table styles seem simple enough to understand, you might feel that there seems to be a lot of things to memorize. However, as we will discuss later, Microsoft has an application that simplifies the development of ASP.NET code. In fact, all of the presentation code described in this section was created by "click and drag," using the application without any manual coding.
|
Related Reading
ASP.NET Cookbook |
The resulting code is a lot easier to maintain than its classic ASP counterpart. After pulling the data records from the database, there are no further string concatenations that clutter up the code. All layout instructions are written in "almost-English" notation in the presentation block. Even a person not fully familiar with HTML can understand the layout specifications.
Summary
In this first introduction to ASP.NET, we have seen that ASP.NET can be thought of as a scalpel that cleanly separates the script-code block from the presentation markup elements. It provides us with a framework to structure our code along the lines of the way we "think" about the logic flow in our minds. In the example considered above, we may think of the logic flow as simply:
- Extract records from database tables.
- Assign records en masse to presentation elements without considering the presentation of each record individually.
- Finally, in a separate block, specify how the presentation elements should display in a browser by setting appropriate attributes.
In classic ASP, on the other hand, the last two items are intertwined; the assignment of the records to the
presentation elements is done together, making it tedious to later modify. Hence, I deliberately elected to approach ASP.NET using
the <asp:datagrid> ... </asp:datagrid> presentation element since I believe it helps to rapidly
motivate and get across the main ideas.
In the next article, we will continue the development of ASP.NET and learn how to write a complete ASP.NET page. We will also study a few more presentation elements, including some that can dramatically simplify writing JavaScript for HTML form validation.
Related Links and References
- ASP.NET in a Nutshell, G. Andrew Duthie, Matthew MacDonald, O'Reilly, June 2002
- ASP.NET Cookbook, Michael A. Kittel, Geoffrey T. LeBlond, O'Reilly, August 2004
Neel Mehta has a doctorate from the University of Pennsylvania and is an ardent fan of .NET and sees it as one of the few technologies that will be around for some time.
Return to ONDotnet.com


