<asp:Table> Control

XHTML tables are one of the most popular ways of structuring a Web page and arranging information for display. At the same time, tables can be tedious to code with all the <tr> and <td> tags to code when surrounding large collections of data. When script output is displayed in table form, however, the task becomes much simpler. The script itself can generate the table rows and table cells saving the programmer from this chore.

The <asp:Table> control is made for scripting the creation of tables. It defines the general structure of a table within which scripts can fill in the rows and columns. The general format for the <asp:Table> control is shown below.

<asp:Table id="id" Runat="Server"
  BackImageUrl="url"
  Caption="string"
  CaptionAlign="Bottom|Left|Right|Top"
  CellSpacing="n"
  CellPadding="n"
  GridLines="None|Horizontal|Vertical|Both"
  HorizontalAlign="Left|Center|Right"
    property="value"...
>
	
  <asp:TableRow id="id" Runat="Server">
    HorizontalAlign="Left|Center|Right"
    VerticalAlign="Top|Middle|Bottom"
      property="value"...
  >
 
    <asp:TableCell id="id" Runat="Server"
      ColumnSpan="colcount"
      HorizontalAlign="Left|Center|Right"
      RowSpan="rowcount"
      Text="value"
      VerticalAlign="Top|Middle|Bottom"
      Wrap="True|False"
        property="value"...
     >
		 
      Cell text
			
    </asp:TableCell>

  </asp:TableRow>

</asp:Table>
Figure 4-33. General format for <asp:Table> control.

The <asp:Table> control contains one or more <asp:TableRow> controls which, in turn, contain one or more <asp:TableCell> controls depending on the dimensions of the table. When using this control to code a static table, all of these controls are required in order to format its rows and columns. This makes for an excessive amount of tedious coding since using standard <tr> and <td> tags is much less work. However, when creating a table under script control, only the single <asp:Table> control needs to be defined to allocate an area on the page where the rows and columns can be generated automatically by a script.

Scripting Tables

When building a table with a script, a Table control is coded on the page to identify the location of the table. An id must be assigned for reference in the script. A standard table layout with gridlines is produced with the GridLines="Both" property. The table is aligned on the page with HorizontalAlign (default Left). CellPadding and CellSpacing properties work like comparable attributes in XHTML tables. A caption is supplied in the Caption property and appears at the CaptionAlign position (default Top) relative to the table.

The following code allocates space for a table to display books from the BookDB.mdb database, output of which appears below.

<asp:Table id="BooksTable" Runat="Server"
  Caption="<b>Table 1. Listing of Books Database</b>"
  CaptionAlign="Left"
  GridLines="Both"/>
Listing 4-48. Coding a Table control for script output.

Table 1. Listing of Books Database
IDTypeTitleAuthorPriceQty
DB111DatabaseOracle DatabaseK. Loney69.9910
DB222DatabaseDatabases in DepthC. J. Date29.956
DB333DatabaseDatabase ProcessingD. Kroenke136.6512
DB444DatabaseAccess Database DesignS. Roman34.9525
DB555DatabaseSQL Server 2005P. Debetta29.990
GR111GraphicsAdobe Photoshop CS2Adobe29.994
GR222GraphicsLearning Web DesignJ. Niederst39.958
GR333GraphicsMacromedia Flash ProfessionalT. Green44.9917
GR444GraphicsDigital Photographer HandbookM. Freeman24.9522
GR555GraphicsCreating Motion GraphicsT. Meyer59.9513
HW111HardwareHow Computers WorkR. White29.998
HW222HardwareUpgrading and Repairing PCsS. Mueller59.995
HW333HardwareUSB System ArchitectureD. Anderson49.991
HW444HardwareDesigning Embedded HardwareJ. Catsoulis44.953
HW555HardwareContemporary Logic DesignR. Katz102.952
SW111SoftwareJava How to ProgramDeitel98.599
SW222SoftwareC Programming LanguageB. Kernighan44.2512
SW333SoftwareProgramming C#J. Liberty44.950
SW444SoftwareProgramming PHPR. J. Lerdorf39.9517
SW555SoftwareVisual Basic.NET ProgrammingP. Vick49.9913
SY111SystemsOperating System ConceptsA. Silberschatz95.751
SY222SystemsThe UNIX Operating SystemJ. D. Peek19.9512
SY333SystemsWindows Server 2003W. R. Stanek29.9925
SY444SystemsLinux in a NutshellS. Figgins44.9514
SY555SystemsMastering Active DirectoryR. R. King49.998
WB111WebAjax in ActionD. Crane22.6714
WB222WebProfessional ASP.NET 2.0B. Evjen32.9921
WB333WebCascading Style SheetsE. A. Meyer39.956
WB444WebDOM ScriptingJ. Keith23.098
WB555WebMicrosoft ASP.NET 2.0D. Esposito29.9912

Figure 4-34. Using a Table control to display database information.

Adding Rows and Columns to a Table

The script to build a table programmatically adds rows and columns to the table. These elements are added by creating new TableRow and TableCell objects, assigning data values and styles to these objects, and using their Add() method to append them to the table. The general formats used to create a table row and table cell are shown below.

Dim row As New TableRow
tableId.Rows.Add(row)

  Dim cell As New TableCell
  cell.Text = "value"
  row.Cells.Add(cell)
Figure 4-35. General formats for adding rows and columns to an <asp:Table> control.

A table is comprised of a Rows collection, a set of individual row objects created for the table. A table row is created by first creating a new TableRow object and assigning it a reference name. The row can be styled with server or CSS style properties. This row is then added to the table's Rows collection through its Add() method.

A row object has a Cells collection to which is added any number of table cells created as named TableCell objects. A value is assigned to the cell through its Text property; the cell also can be styled with server or CSS style properties. After this cell object has been created, it is added to the row's Cells collection through its Add() method. These steps of adding rows and cells are repeated for as many rows and cells as are needed to build the table.

With scripting, much of the work of building table rows and cells can be automated. Normally, when populating a table from an external data source, only a single row needs to be defined. This row definition is repeated by iterating the script for all the records in the retrieved recordset.

The following Page_Load subprogram builds the table of books displayed above. You should recognize the script layout from previous scripts that iterate a recordset. The returned recordset contains six fields that are displayed in the table: BookID, BookType, BookTitle, BookAuthor, BookPrice, and BookQty.

<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Drawing" %>

<SCRIPT Runat="Server">

Sub Page_Load
  
  Dim DBConnection As OleDbConnection
  Dim DBCommand As OleDbCommand
  Dim DBReader As OleDbDataReader
  Dim SQLString As String
    
  DBConnection = New OleDbConnection( _
    "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=" & Server.MapPath("../Databases/BooksDB.mdb"))
  DBConnection.Open()
  SQLString = "SELECT BookID, BookType, BookTitle, BookAuthor, " & _
              "BookPrice, BookQty FROM Books ORDER BY BookID"
  DBCommand = New OleDbCommand(SQLString, DBConnection)
  DBReader = DBCommand.ExecuteReader()
  
  '-- Add a column header row to the table
  Dim HeaderRow As New TableRow
  HeaderRow.Font.Bold = True 
  HeaderRow.HorizontalAlign = HorizontalAlign.Center
  HeaderRow.BackColor = Color.FromName("#F0F0F0")
  HeaderRow.Font.Size = FontUnit.Parse("11pt")
  BooksTable.Rows.Add(HeaderRow)
    
    Dim HeaderCell_1 As New TableCell
    HeaderCell_1.Text = "ID"
    HeaderRow.Cells.Add(HeaderCell_1)
    
    Dim HeaderCell_2 As New TableCell
    HeaderCell_2.Text = "Type"
    HeaderRow.Cells.Add(HeaderCell_2)
    
    Dim HeaderCell_3 As New TableCell
    HeaderCell_3.Text = "Title"
    HeaderRow.Cells.Add(HeaderCell_3)
    
    Dim HeaderCell_4 As New TableCell
    HeaderCell_4.Text = "Author"
    HeaderRow.Cells.Add(HeaderCell_4)
    
    Dim HeaderCell_5 As New TableCell
    HeaderCell_5.Text = "Price"
    HeaderRow.Cells.Add(HeaderCell_5)
    
    Dim HeaderCell_6 As New TableCell
    HeaderCell_6.Text = "Qty"
    HeaderRow.Cells.Add(HeaderCell_6)
    
  While DBReader.Read()
    
    '-- Add a table row
    Dim DataRow As New TableRow
    DataRow.Font.Size = FontUnit.Parse("11pt")
    BooksTable.Rows.Add(DataRow)
      
      '-- Add table cells to row
      Dim DataCell_1 As New TableCell
      DataCell_1.Text = DBReader("BookID")
      DataRow.Cells.Add(DataCell_1)
      
      Dim DataCell_2 As New TableCell
      DataCell_2.Text = DBReader("BookType")
      DataRow.Cells.Add(DataCell_2)
      
      Dim DataCell_3 As New TableCell
      DataCell_3.Text = DBReader("BookTitle")
      DataRow.Cells.Add(DataCell_3)
      
      Dim DataCell_4 As New TableCell
      DataCell_4.Text = DBReader("BookAuthor")
      DataRow.Cells.Add(DataCell_4)
      
      Dim DataCell_5 As New TableCell
      DataCell_5.HorizontalAlign = HorizontalAlign.Right
      DataCell_5.Text = FormatNumber(DBReader("BookPrice"))
      DataRow.Cells.Add(DataCell_5)
      
      Dim DataCell_6 As New TableCell
      DataCell_6.HorizontalAlign = HorizontalAlign.Right
      DataCell_6.Text = DBReader("BookQty")
      DataRow.Cells.Add(DataCell_6)
      
  End While
  
  DBReader.Close()
  DBConnection.Close()

End Sub

</SCRIPT>
Listing 4-49. Code for creating a Table with script.

The first row added to the table comprise the column headings. As described above, a TableRow object (HeaderRow) is declared and various server style properties are assigned to the row which is added to the table's Rows collection. Then TableCell objects are created for each of the columns. Their Text properties are assigned appropriate header text, and the cells are added to the row's Cells collection.

'-- Add a column header row to the table
Dim HeaderRow As New TableRow
HeaderRow.Font.Bold = True 
HeaderRow.HorizontalAlign = HorizontalAlign.Center
HeaderRow.BackColor = Color.FromName("#F0F0F0")
HeaderRow.Font.Size = FontUnit.Parse("11pt")
BooksTable.Rows.Add(HeaderRow)
  
  Dim HeaderCell_1 As New TableCell
  HeaderCell_1.Text = "ID"
  HeaderRow.Cells.Add(HeaderCell_1)
  
  Dim HeaderCell_2 As New TableCell
  HeaderCell_2.Text = "Type"
  HeaderRow.Cells.Add(HeaderCell_2)
  
  Dim HeaderCell_3 As New TableCell
  HeaderCell_3.Text = "Title"
  HeaderRow.Cells.Add(HeaderCell_3)
  
  Dim HeaderCell_4 As New TableCell
  HeaderCell_4.Text = "Author"
  HeaderRow.Cells.Add(HeaderCell_4)
  
  Dim HeaderCell_5 As New TableCell
  HeaderCell_5.Text = "Price"
  HeaderRow.Cells.Add(HeaderCell_5)
  
  Dim HeaderCell_6 As New TableCell
  HeaderCell_6.Text = "Qty"
  HeaderRow.Cells.Add(HeaderCell_6)
Listing 4-50. Code to create a Table header.

After the heading row is added to the table, the recordset is iterated to produce a table row for each record. A TableRow object (DataRow) is created for displaying a database record and is added to the table's Rows collection. Within this row, six TableCell objects are created for the six recordset fields. The field value is assigned as the Text property of the cell, and the cell is added to the row's Cells collection. After iterating the recordset, as many rows are produced as there are records in the recordset.

While DBReader.Read()
  
  '-- Add a table row
  Dim DataRow As New TableRow
  DataRow.Font.Size = FontUnit.Parse("11pt")
  BooksTable.Rows.Add(DataRow)
    
    '-- Add table cells to row
    Dim DataCell_1 As New TableCell
    DataCell_1.Text = DBReader("BookID")
    DataRow.Cells.Add(DataCell_1)
    
    Dim DataCell_2 As New TableCell
    DataCell_2.Text = DBReader("BookType")
    DataRow.Cells.Add(DataCell_2)
    
    Dim DataCell_3 As New TableCell
    DataCell_3.Text = DBReader("BookTitle")
    DataRow.Cells.Add(DataCell_3)
    
    Dim DataCell_4 As New TableCell
    DataCell_4.Text = DBReader("BookAuthor")
    DataRow.Cells.Add(DataCell_4)
    
    Dim DataCell_5 As New TableCell
    DataCell_5.HorizontalAlign = HorizontalAlign.Right
    DataCell_5.Text = FormatNumber(DBReader("BookPrice"))
    DataRow.Cells.Add(DataCell_5)
    
    Dim DataCell_6 As New TableCell
    DataCell_6.HorizontalAlign = HorizontalAlign.Right
    DataCell_6.Text = DBReader("BookQty")
    DataRow.Cells.Add(DataCell_6)
      
End While
Listing 4-51. Code to create a Table row.

Scripting a Table with XHTML Tags

Using an <asp:Table> control is only one of the ways to create a dynamic, script-created table. You still have the option of creating the table with standard XHTML tags written by script to an output area such as a Label control. The following output is identical to that produced with the above Table control. In this case, XHTML table tags are interspersed with database information and written to a Label control. You should recognize this technique from previous scripts.

Table 1. Listing of Books Database
IDTypeTitleAuthorPriceQty
DB111DatabaseOracle DatabaseK. Loney$69.9910
DB222DatabaseDatabases in DepthC. J. Date$29.956
DB333DatabaseDatabase ProcessingD. Kroenke$136.6512
DB444DatabaseAccess Database DesignS. Roman$34.9525
DB555DatabaseSQL Server 2005P. Debetta$29.990
GR111GraphicsAdobe Photoshop CS2Adobe$29.994
GR222GraphicsLearning Web DesignJ. Niederst$39.958
GR333GraphicsMacromedia Flash ProfessionalT. Green$44.9917
GR444GraphicsDigital Photographer HandbookM. Freeman$24.9522
GR555GraphicsCreating Motion GraphicsT. Meyer$59.9513
HW111HardwareHow Computers WorkR. White$29.998
HW222HardwareUpgrading and Repairing PCsS. Mueller$59.995
HW333HardwareUSB System ArchitectureD. Anderson$49.991
HW444HardwareDesigning Embedded HardwareJ. Catsoulis$44.953
HW555HardwareContemporary Logic DesignR. Katz$102.952
SW111SoftwareJava How to ProgramDeitel$98.599
SW222SoftwareC Programming LanguageB. Kernighan$44.2512
SW333SoftwareProgramming C#J. Liberty$44.950
SW444SoftwareProgramming PHPR. J. Lerdorf$39.9517
SW555SoftwareVisual Basic.NET ProgrammingP. Vick$49.9913
SY111SystemsOperating System ConceptsA. Silberschatz$95.751
SY222SystemsThe UNIX Operating SystemJ. D. Peek$19.9512
SY333SystemsWindows Server 2003W. R. Stanek$29.9925
SY444SystemsLinux in a NutshellS. Figgins$44.9514
SY555SystemsMastering Active DirectoryR. R. King$49.998
WB111WebAjax in ActionD. Crane$22.6714
WB222WebProfessional ASP.NET 2.0B. Evjen$32.9921
WB333WebCascading Style SheetsE. A. Meyer$39.956
WB444WebDOM ScriptingJ. Keith$23.098
WB555WebMicrosoft ASP.NET 2.0D. Esposito$29.9912

Figure 4-36. Using a Label control to display database information in a table.
<%@ Import Namespace="System.Data.OleDb" %>

<SCRIPT Runat="Server">

Sub Page_Load
  
  Dim DBConnection As OleDbConnection
  Dim DBCommand As OleDbCommand
  Dim DBReader As OleDbDataReader
  Dim SQLString As String
  
  DBConnection = New OleDbConnection( _
    "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=" & Server.MapPath("../Databases/BooksDB.mdb"))
  DBConnection.Open()
  SQLString = "SELECT BookID, BookType, BookTitle, BookAuthor, " & _
              "BookPrice, BookQty FROM Books ORDER BY BookID"
  DBCommand = New OleDbCommand(SQLString, DBConnection)
  DBReader = DBCommand.ExecuteReader()
  
  TableOut.Text = "<table id=""Books"" border=""1"" cellpadding=""1"">"
  TableOut.Text &= "<caption>Table 1. Listing of Books Database</caption>"
  TableOut.Text &= "<tr>"
  TableOut.Text &= "<th>ID</th>"
  TableOut.Text &= "<th>Type</th>"
  TableOut.Text &= "<th>Title</th>"
  TableOut.Text &= "<th>Author</th>"
  TableOut.Text &= "<th>Price</th>"
  TableOut.Text &= "<th>Qty</th>"
  TableOut.Text &= "</tr>"
  
  While DBReader.Read()
    TableOut.Text &= "<tr>"
    TableOut.Text &= "<td>" & DBReader("BookID") & "</td>"
    TableOut.Text &= "<td>" & DBReader("BookType") & "</td>"
    TableOut.Text &= "<td>" & DBReader("BookTitle") & "</td>"
    TableOut.Text &= "<td>" & DBReader("BookAuthor") & "</td>"
    TableOut.Text &= "<td class=""right"">" & DBReader("BookPrice") & "</td>"
    TableOut.Text &= "<td class=""right"">" & DBReader("BookQty") & "</td>"
    TableOut.Text &= "</tr>"
  End While

  TableOut.Text &= "</table>"
	
  DBReader.Close()
  DBConnection.Close()

End Sub

</SCRIPT>

<form Runat="Server">

<style type="text/css">
  table#Books td      {font-family:times new roman; font-size:11pt}
  table#Books th      {font-family:times new roman; font-size:11pt;
                       background-color:#F0F0F0}
  table#Books caption {font-family:times new roman; font-size:11pt;
                       text-align:left}
  .right              {text-align:right}
</style>

<asp:Label id="TableOut" Runat="Server"/>

</form>
Listing 4-52. Code to create an XHTML table displayed in a Label control.

It is a matter of programmer preference whether to use a Table control or to create a Label area on the page for writing standard table XHTML to the area. As you have already seen, there is a third method for creating output tables that requires no scripting at all—using a GridView, for example. Still, some developers prefer the sense of control given by writing explicit script to produce explicit output.