Section 16.3. Displaying the Output


16.3. Displaying the Output

This time, we'll create a new ASP.NET web site, called AmazonSalesRanks, to display the information returned from Amazon. Drag three GridView objects onto the form, but don't set up their data-binding; we'll do so by hand. Example 16-3 shows the complete .aspx page, including the message printed above the grids, the titles for the grids, the last update label, and the text box used to decide how many rows to show in each grid.

Example 16-3. Displaying the output
<%@ Page Language="C#" CompileWith="Default.aspx.cs"  ClassName="Default_aspx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"                            "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">     <title>Sales Ranks</title> </head> <body>     <form  runat="server">     <div>         The data found here is from the Amazon Web Service and          is stored in a local database. The data is updated every 15         <br />         minutes. This is a work in progress.<br />         &nbsp;<br />         <b>ASP Titles</b>         <asp:GridView  Runat="server"          OnRowDataBound="RowDataBound"         AutoGenerateColumns="false"         HeaderStyle-BackColor="PapayaWhip"         BorderColor="#000099"         AlternatingRowStyle-BackColor="LightGrey"         HeaderStyle-Font-Bold=true         Width="900">             <Columns>                 <asp:TemplateField HeaderStyle-Width ="10">                     <HeaderTemplate>                         Position                     </HeaderTemplate>                     <ItemTemplate>                         <asp:Label Runat="server" >                           <%# rowNumber %></asp:Label>                     </ItemTemplate>                 </asp:TemplateField>                 <asp:TemplateField>                     <HeaderTemplate>                         Title                     </HeaderTemplate>                     <ItemTemplate>                    <a href="http://www.amazon.com/exec/obidos/ASIN/<%#                             Eval("isbn")%>/" target="_blank"><%#                             Eval("title") %></a>                     </ItemTemplate>                 </asp:TemplateField>                 <asp:BoundField HeaderText="Author"                    ReadOnly="true" DataField="Author" />                 <asp:BoundField HeaderText="Publisher"                    ReadOnly="true" DataField="Publisher" />                 <asp:BoundField HeaderText="Publish Date"                    ReadOnly="true" DataField="pubDate" />                 <asp:BoundField HeaderText="Rank"                     ReadOnly="true" DataField="Rank"                     DataFormatString="{0:N0}"                     ItemStyle-HorizontalAlign="right" />             </Columns>         </asp:GridView>         <br />                 <b>ASP Titles</b>         <asp:GridView  Runat="server"         OnRowDataBound="RowDataBound"         AutoGenerateColumns="false"         HeaderStyle-BackColor="PapayaWhip"         BorderColor="#000099"         AlternatingRowStyle-BackColor="LightGrey"         HeaderStyle-Font-Bold=true         Width="900">             <Columns>                 <asp:TemplateField HeaderStyle-Width ="10">                     <HeaderTemplate>                         Position                     </HeaderTemplate>                     <ItemTemplate>                         <asp:Label Runat="server" >                           <%# rowNumber %></asp:Label>                     </ItemTemplate>                 </asp:TemplateField>                 <asp:TemplateField>                     <HeaderTemplate>                         Title                     </HeaderTemplate>                     <ItemTemplate>                       <a href="http://www.amazon.com/exec/obidos/ASIN/<%#                             Eval("isbn")%>/" target="_blank"><%#                             Eval("title") %></a>                     </ItemTemplate>                 </asp:TemplateField>                 <asp:BoundField HeaderText="Author"                   ReadOnly="true" DataField="Author" />                 <asp:BoundField HeaderText="Publisher"                   ReadOnly="true" DataField="Publisher" />                 <asp:BoundField HeaderText="Publish Date"                   ReadOnly="true" DataField="pubDate" />                 <asp:BoundField HeaderText="Rank"                   ReadOnly="true" DataField="Rank"                   DataFormatString="{0:N0}"                   ItemStyle-HorizontalAlign="right" />             </Columns>         </asp:GridView>         <br />         <b>VB Titles</b>         <asp:GridView  Runat="server"         OnRowDataBound="RowDataBound"         AutoGenerateColumns="false"         HeaderStyle-BackColor="PapayaWhip"         BorderColor="#000099"         AlternatingRowStyle-BackColor="LightGrey"         HeaderStyle-Font-Bold=true         Width="900">             <Columns>                 <asp:TemplateField HeaderStyle-Width ="10">                     <HeaderTemplate>                         Position                     </HeaderTemplate>                     <ItemTemplate>                         <asp:Label Runat="server" >                           <%# rowNumber %></asp:Label>                     </ItemTemplate>                 </asp:TemplateField>                 <asp:TemplateField>                     <HeaderTemplate>                         Title                     </HeaderTemplate>                     <ItemTemplate>                       <a href="http://www.amazon.com/exec/obidos/ASIN/<%#                             Eval("isbn")%>/" target="_blank"><%#                             Eval("title") %></a>                     </ItemTemplate>                 </asp:TemplateField>                 <asp:BoundField HeaderText="Author"                   ReadOnly="true" DataField="Author" />                 <asp:BoundField HeaderText="Publisher"                   ReadOnly="true" DataField="Publisher" />                 <asp:BoundField HeaderText="Publish Date"                   ReadOnly="true" DataField="pubDate" />                 <asp:BoundField HeaderText="Rank"                   ReadOnly="true" DataField="Rank"                   DataFormatString="{0:N0}"                   ItemStyle-HorizontalAlign="right" />             </Columns>         </asp:GridView>         <asp:Label  Runat="server"           Text="Last Update"></asp:Label>         <br />         Number to show in grid:         <asp:TextBox  Runat="server"           Width="48px" Height="22px"           AutoPostBack="True"></asp:TextBox>     </div>     </form> </body> </html>

The key aspect of the HTML is the creation of three GridViews. They each work the same way, so we'll focus on the first:

<asp:GridView  Runat="server"   OnRowDataBound="RowDataBound"  AutoGenerateColumns="false"  HeaderStyle-BackColor="PapayaWhip"  BorderColor="#000099"  AlternatingRowStyle-BackColor="LightGrey"  HeaderStyle-Font-Bold=true  Width="900">

The GridView is named gvASP. A few properties are set, the most important of which is the event handler for the OnRowDataBound event and the Boolean property AutoGenerateColumns, which is set to False. This allows you to take direct control of the columns, which you do by creating a columns element:

<columns>   ... </columns>

The first column within the columns element is a template field column element. A template field column allows you to insert controls into the column. In the first instance, you'll insert a Headertemplate (used to create a column header) with the text Position, and an asp:label control. That label will display, as its text, a row number. The mechanism for generating this row number is discussed in "Handling the RowDataBound Event," later in this chapter.

<asp:TemplateField HeaderStyle-Width ="10">     <HeaderTemplate>         Position     </HeaderTemplate>     <ItemTemplate>         <asp:Label Runat="server" ><%# rowNumber %></asp:Label>     </ItemTemplate>

For a full explanation of template fields and the other elements used in this page, please see Programming ASP.NET (O'Reilly).


The second column is also a template field, this time with the column heading Title. The title itself is displayed by evaluating the title column in the current row in the data set to which this GridView is bound, and surrounding that title with a link to the appropriate page on Amazon.com. This makes the title a hyperlink the user can click.

<asp:TemplateField>     <HeaderTemplate>         Title     </HeaderTemplate>     <ItemTemplate>         <a href="http://www.amazon.com/exec/obidos/ASIN/         <%# Eval("isbn")%>/" target="_blank"><%# Eval("title") %></a>     </ItemTemplate> </asp:TemplateField>

Let's take this apart. The first element is the template field:

<asp:TemplateField>  </asp:TemplateField>

Within the template field are two template elements: the header and the item. The header is pretty straightforward. It has simple text (though it could have any kind of HTML):

<headertemplate>      Title </headertemplate>

The item template is a bit trickier:

<itemtemplate>     <a href="http://www.amazon.com/exec/obidos/ASIN/<%# Eval("isbn")%>/"               target="_blank"><%# Eval("title") %></a> </itemtemplate>

Note that you'll want to test the title (and all other strings) to ensure that it is valid HTML.


We'll evaluate this one from the outside in. The first thing to notice is the start of a normal hyperlink:

<a href="http://www.amazon.com/exec/obidos/ASIN/

However, the hyperlink is then appended with the result of evaluating the ISBN from the bound data:

<%# Eval("isbn") %>/"

This hyperlink tag has an attribute:

target="_blank"

That attribute causes the link to open a new instance of the browser. The body of the link (the displayed text of the link) is also an evaluated value:

Eval("title")

If the bound data has the title Programming Visual Basic .NET, Second Edition, and the ISBN 0596004389, this item emits the following HTML:

<a href=http://www.amazon.com/exec/obidos/ASIN/0596004389/    target="_ blank">Programming Visual Basic .NET 2nd Edition </a>

The first two columns are tricky. The first is tricky because we need to do some work to create the rowNumber (see the code that follows), and the second because we need to wrap the bound value (the ISBN and the title) inside a hyperlink. The next four columns are easier; they are just bound to the data.

The first bound column has the header text Author, is marked as readOnly, and is bound to the author column in the row of the DataSet table to which this GridView is bound:

<asp:BoundColumn HeaderText="Author"    ReadOnly="true"     DataField="author"/>

Notice that this is a self-closing element, as are the next three bound columns:

<asp:BoundColumn HeaderText="Publisher"     ReadOnly="true"     DataField="publisher"/> <asp:BoundColumn HeaderText="Publish Date"    ReadOnly="true"     DataField="pubdate"/> <asp:BoundColumn HeaderText="Rank"     ReadOnly="true"     DataField="Rank" DataFormatString="{0:N0}"    ItemStyle-HorizontalAlign="Right"/>

16.3.1. Implementing the Grid

The complete source code for the code-behind file is shown in Example 16-4, followed by the analysis.

Example 16-4. Code-behind file for SalesDisplay
using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Default_aspx {    protected int showRecords;    protected int totalASP;    protected int totalCSharp;    protected int rowNumber = 0;    protected override void OnLoad( EventArgs e )    {       // initialize number of records to show to 7       if ( !IsPostBack )       {          showRecords = 7;       }       // if it is a post back, get the number       // from the text box       else       {          showRecords = Convert.ToInt32( txtShowRecords.Text );       }       // connect to the db       string connectionString =       "server=localhost;Trusted_Connection=true;database=AmazonSalesRanks";       // pick records to display       string commandString =          @"Select top " + showRecords +          " * from BookInfo where technology = 'ASPNET' order by rank";       SqlDataAdapter dataAdapter =          new SqlDataAdapter( commandString, connectionString );       DataSet dataSet = new DataSet( );       dataAdapter.Fill( dataSet, "aspBookInfo" ); // first table       commandString = @"Select top " + showRecords + " *                     from BookInfo where technology = 'CSHARP' order by rank";       dataAdapter = new SqlDataAdapter( commandString, connectionString );       dataAdapter.Fill( dataSet, "csBookInfo" ); // second table       commandString = @"Select top " + showRecords +          " * from BookInfo where technology = 'VBNET' order by rank";       dataAdapter = new SqlDataAdapter( commandString,          connectionString );       dataAdapter.Fill( dataSet, "vbBookInfo" ); // third table       // create the data view and bind to the grid       DataView aspDataView =          dataSet.Tables[0].DefaultView;       gvASP.DataSource = aspDataView;       gvASP.DataBind( );       rowNumber = 0;       DataView csDataView = dataSet.Tables[1].DefaultView;       gvCSharp.DataSource = csDataView;       gvCSharp.DataBind( );       rowNumber = 0;       DataView vbDataView = dataSet.Tables[2].DefaultView;       this.gvVBNet.DataSource = vbDataView;       gvVBNet.DataBind( );       // txtShowRecords.DataBind( );       lblLastUpdate.Text = "Last updated: " +          dataSet.Tables[2].Rows[0]["lastUpdate"].ToString( );    }    void RowDataBound( object sender, GridViewRowEventArgs e )    {       this.rowNumber++;    } }

The program begins by declaring a number of local variables, the most important of which is the rowNumber, which is initialized to 0:

protected int rowNumber = 0;

The showRecords member variable is used to keep track of how many records to display, and when the page is first displayed, showRecords is set to 7 (a safe and reasonable default). On subsequent postbacks of the page, that value is set to whatever is in the text box:

private void Page_Load(object sender, System.EventArgs e) {    if (! IsPostBack )    {       showRecords = 7;    }    else    {       showRecords = Convert.ToInt32(txtShowRecords.Text);    }

Continuing in the page-load event handler, the database connection is made and the database is searched, based on the "technology" (i.e., ASP.NET versus C# versus VB.NET):

string connectionString =     "server=localhost;Trusted_Connection=true;database=AmazonSalesRanks"; string commandString =     @"Select top " + showRecords +     " * from BookInfo where technology = 'ASPNET' order by rank"; SqlDataAdapter dataAdapter =     new SqlDataAdapter(commandString, connectionString); DataSet dataSet = new DataSet( ); dataAdapter.Fill(dataSet,"aspBookInfo"); // first table

The same is done for each of the other queries. Once the tables in the data set are created, a data view is created for the first table. This represents a view of the ASP.NET results:

DataView aspDataView =     dataSet.Tables[0].DefaultView;

It is to this data view that the GridView is bound:

gvASP.DataSource = aspDataView;  gvASP.DataBind();

Once this is done, the rowNumber member variable is set back to zero (we'll discuss how it moves from zero in a bit), and the next data view is created and bound to its respective GridView:

rowNumber = 0; DataView csDataView = dataSet.Tables[1].DefaultView; gvCSharp.DataSource = csDataView; gvCSharp.DataBind( );

This is done one final time for the third table:

rowNumber = 0; DataView vbDataView = dataSet.Tables[2].DefaultView; this.gvVBNet.DataSource = vbDataView; gvVBNet.DataBind( );

Finally, the label lblLastUpdate is set from the lastUpdate field in the table:

 lblLastUpdate.Text = "Last updated: " + dataSet.Tables[2].Rows[0]                      ["lastUpdate"].ToString();

16.3.2. Handling the RowDataBound Event

You will remember that when you created the GridView, you bound the RowDataBound event to the RowDataBound method. As a matter of fact, you did this for all three GridViews. Whenever an item is bound on any grid, it is handled in this method. All the method does is to increment the row counter, rowNumber:

public void Item_Bound(Object sender, GridViewItemEventArgs e) {    rowNumber++; }

The net effect is that each time an item is bound to the GridView, the rowNumber is incremented and then displayed in the first templated column, giving you a relative ranking within the GridView.



Programming C#(c) Building. NET Applications with C#
Programming C#: Building .NET Applications with C#
ISBN: 0596006993
EAN: 2147483647
Year: 2003
Pages: 180
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net