48
Processing Web Form Output T his chapter deals with information returned by the application or computer to various Web Form controls. This information is typically viewed on the monitor or sent to a printer or file. In this chapter, you will learn techniques for designing well-formatted output that will enhance your application. Send It Out You have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as much with a combination of images and text. Poorly labeled and formatted information can mean instantaneous death to the most elo- quent application code. C#, used in conjunction with various Web Server tools, provides the programmer with a wide variety of formatting tools for creating meaningful output. The example programs in this section demonstrate the variety of ways information can be displayed. The output topics discussed include the use of the following Web con- trols: AdRotator control Date, string, and numeric formatting Repeater control Tabular output TextBox and Label controls You’ll also find other output techniques, used later in this chapter, for processing list information. This section, however, covers the most frequently used formatting and output techniques in a number of unique cases. C H A P T E R 8 269 5001_Ch08 07/12/01 2.29 pm Page 269

Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

Processing Web Form Output

This chapter deals with information returned by theapplication or computer to various Web Form controls. This information is typically viewedon the monitor or sent to a printer or file. In this chapter, you will learn techniques fordesigning well-formatted output that will enhance your application.

Send It OutYou have heard the saying “One picture is worth a thousand words.” An application’sscreen and printer output can say just as much with a combination of images and text.Poorly labeled and formatted information can mean instantaneous death to the most elo-quent application code. C#, used in conjunction with various Web Server tools, provides theprogrammer with a wide variety of formatting tools for creating meaningful output.

The example programs in this section demonstrate the variety of ways informationcan be displayed. The output topics discussed include the use of the following Web con-trols:

• AdRotator control

• Date, string, and numeric formatting

• Repeater control

• Tabular output

• TextBox and Label controls

You’ll also find other output techniques, used later in this chapter, for processing listinformation. This section, however, covers the most frequently used formatting and outputtechniques in a number of unique cases.

C H A P T E R 8

269

5001_Ch08 07/12/01 2.29 pm Page 269

Prentice Hall PTR
This is a sample chapter of C# for Web Programming ISBN: 0-13-066117-1 For the full text, visit http://www.phptr.com ©2001 Pearson Education. All Rights Reserved.
Page 2: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

Using TextBox or Label Controls

Why would a programmer use a TextBox control for output? First, think of the differencebetween a Label control and a TextBox control in terms of output. The user cannot directlyalter a Label control’s output, while TextBox information can be altered. Label controls arepurely output devices while TextBox controls can serve as input or output devices. Labelcontrols might be the control of choice when displaying information that you do not wantthe user to change.

We have already experimented with TextBox controls in earlier chapters. In this sec-tion, we’ll illustrate output to a TextBox control in preparation for further examples in thischapter.

This project, named TextOut, is designed to take user input in one TextBox control,encrypt the text, and display the encrypted text in another TextBox control. The form andcontrols for this project are shown in Figure 8.1.

Let’s examine the code for the whole project before looking at the technique used toencrypt the text, shown in a bold font.

270 Chapter 8 • Processing Web Form Output

Figure 8.1 The form and controls for the TextOut project.

5001_Ch08 07/12/01 2.29 pm Page 270

Page 3: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;

namespace TextOut{

/// <summary>/// Summary description for WebForm1./// </summary>public class WebForm1 : System.Web.UI.Page{

protected System.Web.UI.WebControls.Label Label1;protected System.Web.UI.WebControls.TextBox TextBox1;protected System.Web.UI.WebControls.Label Label2;protected System.Web.UI.WebControls.TextBox TextBox2;protected System.Web.UI.WebControls.Button Button1;

public WebForm1(){

Page.Init += new System.EventHandler(Page_Init);}

private void Page_Load(object sender,System.EventArgs e)

{// Put user code to initialize the page here

}

private void Page_Init(object sender, EventArgs e){

//// CODEGEN: This call is required by the// ASP.NET Web Form Designer.//InitializeComponent();

}

#region Web Form Designer generated code/// <summary>/// Required method for Designer support - do not

Send It Out 271

5001_Ch08 07/12/01 2.29 pm Page 271

Page 4: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

/// modify the contents of this method with the/// code editor./// </summary>private void InitializeComponent(){

this.Button1.Click += newSystem.EventHandler(this.Button1_Click);

}#endregion

private void Button1_Click(object sender,System.EventArgs e)

{string str1;char oldchar, indexchar;int tempint;

oldchar = ‘A’;

str1 = TextBox1.Text;str1 = str1.ToUpper();

for(int i = 0; i < 26; i++){

tempint = Convert.ToByte(oldchar) + i;indexchar = Convert.ToChar(tempint);

str1 = str1.Replace(indexchar, ‘x’);}

TextBox2.Text = str1;}

}}

This application revolves around a Button1_Click event. When this event is fired,text from the first TextBox control is saved as a string. Each character in the string is thenconverted to uppercase. Then starting with the letter “A” and going through “Z,” the char-acters are replaced with the encrypting character “x.” Examine the for loop in the follow-ing portion of code and see how this action is performed.

Private void Button1_Click (object sender,System.EventArgs e)

{string str1;char oldchar, indexchar;int tempint;

272 Chapter 8 • Processing Web Form Output

5001_Ch08 07/12/01 2.29 pm Page 272

Page 5: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

oldchar = ‘A’;

str1 = TextBox1.Text;str1 = str1.ToUpper();

for(int i = 0; i < 26; i++){

tempint = Convert.ToByte(oldchar) + i;indexchar = Convert.ToChar(tempint);

str1 = str1.Replace(indexchar, ‘x’);}

TextBox2.Text = str1;}

When each character has been converted in the string, the encrypted string is then sentto the TextBox2 control.

The results of this operation are shown in Figure 8.2.

The C# Replace() method is a StringBuilder with all instances of a specified charac-ter replaced with a new character. The specified characters are the letters “A” to “Z” whilethe replacement character is simply the letter “x.”

Send It Out 273

Figure 8.2 Plain text is converted to encrypted text.

5001_Ch08 07/12/01 2.29 pm Page 273

Page 6: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

Of course, it doesn’t take much imagination or programming experience to realizethat an “x” character doesn’t have to be used here. Perhaps you’ll want to continue this proj-ect and come up with a unique way of scrambling the characters. One technique is to add orsubtract an integer value to each character’s value.

While this example shows a unique output situation involving a TextBox control,many times the amount of output requires more than one line of text. One solution might beto use a multiline TextBox control, as you’ll see in the next section.

Using a Multiline TextBox Control

As you know, TextBox controls provide a multiline property that allows the user to printmultiple lines of text within the control. The multiline property is normally set to false.

This project, named MultiLine, is designed to print multiple lines of text to the con-trol. The form and controls for this project are shown in Figure 8.3.

Examine Figure 8.3 and note that the multiline property has been set to true in theProperties pane. Once this is done, the TextBox control can be resized in the Designer pane.

Here is the code for the whole project, with the Button1_Click event shown in a boldfont.

274 Chapter 8 • Processing Web Form Output

Figure 8.3 A TextBox control with the multiline property set to true.

5001_Ch08 07/12/01 2.29 pm Page 274

Page 7: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;

namespace MultiLine{

/// <summary>/// Summary description for WebForm1./// </summary>public class WebForm1 : System.Web.UI.Page{

protected System.Web.UI.WebControls.Button Button1;protected System.Web.UI.WebControls.TextBox TextBox1;

public WebForm1(){

Page.Init += new System.EventHandler(Page_Init);}

private void Page_Load(object sender, EventArgs e){

// Put user code to initialize the page here}

private void Page_Init(object sender, EventArgs e){

//// CODEGEN: This call is required by the ASP.NET// Web Form Designer.//InitializeComponent();

}

#region Web Form Designer generated code/// <summary>/// Required method for Designer support – do/// not modify the contents of this method with/// the code editor./// </summary>private void InitializeComponent(){

Send It Out 275

5001_Ch08 07/12/01 2.29 pm Page 275

Page 8: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

Button1.Click += new System.EventHandler(this.Button1_Click);

this.Load += new System.EventHandler(this.Page_Load);

}#endregion

private void Button1_Click (object sender,System.EventArgs e)

{string mystr;

mystr=”This is a test string that shows that “ +“it is possible to write multiple lines “ +“of text to a TextBox control whose “ +“Multiline property has been set to true. “ +“Of course, it might also be desirable to “ +“format the information being sent to the “ +“TextBox control. Formatting requires “ +“just little additional work!”;

TextBox1.Text = mystr;}

}}

Again, the action in this project takes place when a Button1_Click event is fired. Atthis point a predefined string, named mystr, is transferred to the Text property of theTextBox control as shown in the following portion of code.

private void Button1_Click (object sender,System.EventArgs e)

{string mystr;

mystr=”This is a test string that shows that “ +“it is possible to write multiple lines “ +“of text to a TextBox control whose “ +“Multiline property has been set to true. “ +“Of course, it might also be desirable to “ +“format the information being sent to the “ +“TextBox control. Formatting requires “ +“just little additional work!”;

TextBox1.Text = mystr;}

276 Chapter 8 • Processing Web Form Output

5001_Ch08 07/12/01 2.29 pm Page 276

Page 9: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

While this is a very simple example, it illustrates a couple of points you may not have beenthinking about. First, it illustrates how large strings can be built in C#. It also illustrates that oncethe string is sent to the control’s Text property, the control will format the output of the string tofit within the confines of the control’s size. Figure 8.4 illustrates the project’s output.

The control makes the decision on how the string is displayed. How and when wordsare wrapped to the next line is controlled, in this example, by the control itself—not the pro-grammer or user.

Sending output to a control in this manner is usually fine for strings of text. However,it doesn’t solve the problem of tabular output. Tabular output, most frequently used in pre-senting columns of numbers, requires programming or user intervention. We’ll examine asimple technique for formatting information within a TextBox control in the next section.

Tabular Output Using a TextBox Control

In the previous example, you learned that TextBox controls provide a multiline propertythat allows the user to print multiple lines of text within the control. The example in thissection, named Tabular, takes advantage of the multiline property of the TextBox controland adds additional formatting capabilities.

Send It Out 277

Figure 8.4 Multiple lines of text are sent to the TextBox control.

5001_Ch08 07/12/01 2.29 pm Page 277

Page 10: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

This project is designed to display three columns of numbers. The first column dis-plays the number itself, the second shows the number squared, and the third displays thesquare root of the number.

The form and controls for this project are shown in Figure 8.5.

Examine Figure 8.5 and note that the multiline property has been set to true for theTextBox control in the Properties pane. Once this is done, the TextBox control can beresized in the Designer pane.

Here is the code for the Tabular project, with the Button1_Click event shown in abold font.

using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;

278 Chapter 8 • Processing Web Form Output

Figure 8.5 A multiline TextBox control will display formatted columns of numbers.

5001_Ch08 07/12/01 2.29 pm Page 278

Page 11: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

namespace Tabular{

/// <summary>/// Summary description for WebForm1./// </summary>public class WebForm1 : System.Web.UI.Page{

protected System.Web.UI.WebControls.Button Button1;protected System.Web.UI.WebControls.TextBox TextBox1;

public WebForm1(){

Page.Init += new System.EventHandler(Page_Init);}

private void Page_Load(object sender, EventArgs e){

// Put user code to initialize the page here}

private void Page_Init(object sender, EventArgs e){

//// CODEGEN: This call is required by the ASP.NET// Web Form Designer.//InitializeComponent();

}

#region Web Form Designer generated code/// <summary>/// Required method for Designer support – do/// not modify the contents of this method with/// the code editor./// </summary>private void InitializeComponent(){

Button1.Click += new System.EventHandler(this.Button1_Click);

this.Load += new System.EventHandler(this.Page_Load);

}#endregion

private void Button1_Click (object sender,System.EventArgs e)

{

Send It Out 279

5001_Ch08 07/12/01 2.29 pm Page 279

Page 12: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

string sta, stb, stc, formatstr;string lfcr = “\r\n”;string wholestr = “”;

for(int i = 1; i < 21; i++){

sta = i.ToString();stb = (i*i).ToString();

formatstr = “{0:###.####}”;Double[] arg = new Double[1];arg[0] = Math.Sqrt(i);

stc = string.Format(formatstr, arg[0]);

wholestr += sta + “\t\t” + stb +“\t\t” + stc + lfcr;

}TextBox1.Text = wholestr;

}}

}

In the following portion of code, you will find three strings: sta, stb, and stc. The firststring, sta, holds the original number converted to a string. The second string, stb, holds thesquare of the original number converted to a string. The third string, stc, holds the square rootof the original number after it has been formatted to contain a specified number of digits.

private void Button1_Click (object sender,System.EventArgs e)

{string sta, stb, stc, formatstr;string lfcr = “\r\n”;string wholestr = “”;

for(int i = 1; i < 21; i++){

sta = i.ToString();stb = (i*i).ToString();

formatstr = “{0:###.####}”;Double[] arg = new Double[1];arg[0] = Math.Sqrt(i);

stc = string.Format(formatstr, arg[0]);

wholestr += sta + “\t\t” + stb +

280 Chapter 8 • Processing Web Form Output

5001_Ch08 07/12/01 2.29 pm Page 280

Page 13: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

“\t\t” + stc + lfcr;}TextBox1.Text = wholestr;

}

Note that the string, wholestr, is built up from the individual strings. In addition tothis information, you will notice several tab escape sequences (“\t”) and a carriage returnand line feed (“\r\n”). The tab escape sequences align the columns on each line while thecarriage return and line feed force output to start on a new line.

A variety of escape sequences are shown in Table 8.1. Be careful in how you applyescape sequences to formatted output. Sometimes a little experimentation is required to getthe output just the way you want it.

There is a portion of code from the previous listing that warrants special attention.The String.Format method comes in a variety of flavors, as shown in Table 8.2.

It is not our intention to explain each of these methods beyond what is shown in Table8.2. You might note, however, that this project uses the first String.Format method listedin the table.

Table 8.1 Escape Sequences for Formatting

Escape Sequence Purpose

\a bell (alert)

\b backspace

\f form feed

\n new line

\r carriage return

\t horizontal tab

\v vertical tab

\’ single quotation mark

\” double quotation mark

\\ backslash

\? literal question mark

\ooo ASCII character shown in octal notation

\xhh ASCII character shown in hexadecimal notation

\xhhhh UNICODE character shown in hexadecimal notation when thisescape sequence is used in a wide-character constant or a UNICODEstring literal

Send It Out 281

5001_Ch08 07/12/01 2.29 pm Page 281

Page 14: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

Table 8.2 String.Format Methods

Method Use

String.Format Method Used to replace each format given in a string with the (String, Object[]) textual equivalent of a corresponding object’s value. The

objects are given in an array.

String.Format Method Used to replace each format given in a string with the (String, Object) textual equivalent of a corresponding object’s value.

String.Format Method Used to replace each format given in a string with the (String, Object[], textual equivalent of a corresponding object’s value. The IServiceObjectProvider) objects are given in an array and an IServiceObjectProvider

interface is used to set how formatting is performed.

String.Format Method Used to replace each format given in a string with the (String, Object, Object) textual equivalent of a corresponding object’s value.

String.Format Method Used to replace each format given in a string with(String, Object, Object, Object) the textual equivalent of a corresponding object’s value.

In using this method in our example, the format string, formatstr, is given as“{0:###.####}”. This states that the string specified by arg[0] will be formatted to con-tain no more than three digits to the left of the decimal point and no more than four digits tothe right of the decimal point.

formatstr = “{0:###.####}”;Double[] arg = new Double[1];arg[0] = Math.Sqrt(i);

stc = string.Format(formatstr, arg[0]);

Using String.Format methods, the number of decimal places can be controlled intabular outputs.

Figure 8.6 shows the output from this project as it is sent to the multiline TextBoxcontrol.

This would be a great place for a little experimentation on your part. You might wantto experiment with various escape sequences or with the String.Format methods. Infuture chapters, you’ll see more formatting as other projects are developed.

Sending Output to a Printer

TextBox and Label controls are displayed on your system’s monitor. However, what hap-pens if you want to send information to a printer? First, let us warn you that this topic opensPandora’s box. Once you decide to print something, it becomes very important as to whatyou want to print. Do you want to do a screen dump? Do you want to print a file? Do you

282 Chapter 8 • Processing Web Form Output

5001_Ch08 07/12/01 2.29 pm Page 282

Page 15: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

want to print a table of numeric results generated while the application is running? All ofthese questions are answered with different solutions in code.

Two general categories of solutions are available: printing without the use of thePrintDialog box and printing with the use of the PrintDialog box.

In this section, we’ll show you an example of how to print an external file to thedefault printer without the use of the PrintDialog box.

The code you are about to encounter is a modification of a WinForm printing exampleprovided by Microsoft. This application has been modified to accommodate our Web Formapplications.

As you study this example you’ll notice that the DrawString() method is used to drawthe information on the printer.

This project, named Printing, is designed to print ASCII text from an external text filenamed const.txt found in the root directory of the C: drive. The application provides no format-ting, so it is important that line breaks occur at the end of each line of text.

The form and button control for this project are shown in Figure 8.7.

Here is the code for the Printing project. Note that several lines have been wrapped to thenext line due to length. Also note the code set in a bold font. This code is the key to the project.

Send It Out 283

Figure 8.6 Tabular output in a TextBox control.

5001_Ch08 07/12/01 2.29 pm Page 283

Page 16: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.Drawing.Printing;using System.Web;using System.IO;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;

namespace Printing{

/// <summary>/// Summary description for WebForm1./// </summary>public class WebForm1 : System.Web.UI.Page{

284 Chapter 8 • Processing Web Form Output

Figure 8.7 The form and button control used with the Printing project.

5001_Ch08 07/12/01 2.29 pm Page 284

Page 17: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

protected System.Web.UI.WebControls.Button Button1;protected System.ComponentModel.Container components;protected System.Web.UI.WebControls.Label Label2;protected System.Web.UI.WebControls.Label Label1;protected Font printFont;protected StreamReader streamToPrint;

public WebForm1(){

Page.Init += new System.EventHandler(Page_Init);}

private void Page_Load(object sender, EventArgs e){

// Put user code to initialize the page here}

private void Page_Init(object sender, EventArgs e){

//// CODEGEN: This call is required by the ASP.NET// Web Form Designer.//InitializeComponent();

}

#region Web Form Designer generated code/// <summary>/// Required method for Designer support – do/// not modify the contents of this method with/// the code editor./// </summary>private void InitializeComponent(){

this.components = newSystem.ComponentModel.Container ();

Button1.Click += newSystem.EventHandler (this.Button1_Click);

this.Load += newSystem.EventHandler (this.Page_Load);

}#endregion

private void Button1_Click (object sender,System.EventArgs e)

{try {

Send It Out 285

5001_Ch08 07/12/01 2.29 pm Page 285

Page 18: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

// Place document to print in root// directory of hard disk. Name it// const.txt.streamToPrint = new StreamReader

(“c:\\const.txt”);try {

printFont = new Font(“Arial”, 12);PrintDocument pd = new PrintDocument();pd.PrintPage += new PrintPageEventHandler

(this.pd_PrintPage);// Set your printer’s name. Obtain from// System’s Printer Dialog Box. pd.PrinterSettings.PrinterName =

“HP DeskJet 930C Series”;pd.Print();

}finally {

streamToPrint.Close();}

}catch(Exception ex) {

Label2.Text = “Error printing file: “ +ex.ToString();

}}

// The event fired for each page to print.private void pd_PrintPage(object sender,

PrintPageEventArgs ev) {float lpp = 0;float ypos = 0;int counter = 0;float leftMar = ev.MarginBounds.Left;float topMar = ev.MarginBounds.Top;string textline = null;

// calculate number of lines per page,// using the MarginBounds.lpp = ev.MarginBounds.Height /

printFont.GetHeight(ev.Graphics);

// Iterate over the file, printing each line.while(counter < lpp &&

((textline=streamToPrint.ReadLine())!= null)) {

ypos = topMar +(counter *printFont.GetHeight(ev.Graphics));

286 Chapter 8 • Processing Web Form Output

5001_Ch08 07/12/01 2.29 pm Page 286

Page 19: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

ev.Graphics.DrawString(textline, printFont,Brushes.Black,leftMar, ypos,new StringFormat());

counter++;}

// More lines? Print another pageif(textline != null)

ev.HasMorePages = true;else

ev.HasMorePages = false;}

public override void Dispose() {base.Dispose();components.Dispose();

}}

}

Let’s examine the important portions of code to gain an understanding of how thistechnique works.

First, make sure the following namespaces are also included in the project.

using System.Drawing.Printing;using System.ComponentModel;using System.IO;using System.Collections;

The StreamReader() method is used to read a stream. The first time this method isencountered in the project, it is used to obtain the file that will be printed to the printer.

try {streamToPrint = new StreamReader

(“c:\\const.txt”);

Here the StreamReader() method reads characters from the current stream andreturns the data as a string.

The DrawString() method requires a font and a brush color. The following line ofcode sets the font to a 12 point Arial font.

try {printFont = new Font(“Arial”, 12);

The PrintDocument class is a member of the System.Drawing.Printing name-space. This class is responsible for defining a reusable object that will send output to theprinter.

Send It Out 287

5001_Ch08 07/12/01 2.29 pm Page 287

Page 20: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

The pd.PrintPage event occurs when a page is printed. The event handler receives aPrintPageEventArgs that contains data related to the PrintPage event.

PrintDocument pd = new PrintDocument();pd.PrintPage += new PrintPageEventHandler

(this.pd_PrintPage);// Set your printer’s name. Obtain from// System’s Printer Dialog Box. pd.PrinterSettings.PrinterName =

“HP DeskJet 930C Series”;pd.Print();

The pd.Print() method then prints the document to the printer. The printer is identi-fied by using the PrinterSettings property. In this example, the printer is a HP DeskJet 930CSeries printer.

The next portion of code closes the StreamReader and returns any system resourcesassociated with the reader.

finally {streamToPrint.Close();

}

If an exception occurs, the following portion of code will alert the user by printing thismessage and the exception as the Label2 control’s text.

catch(Exception ex) {Label2.Text = “Error printing file: “ +

ex.ToString();}

The pd_PrintPage() method is responsible for sending the correct number of lines tothe printer for each page to be printed. As a result, a number of variables are declared at the startof this method. They will be used to set the drawing parameters for the DrawString() method.

// The event fired for each page to print.private void pd_PrintPage(object sender,

PrintPageEventArgs ev) {float lpp = 0;float ypos = 0;int counter = 0;float leftMar = ev.MarginBounds.Left;float topMar = ev.MarginBounds.Top;string textline = null;

For example, the value for the lpp variable is calculated by knowing the Margin-Bounds.Height value then dividing it by the height of the font used when printing.

288 Chapter 8 • Processing Web Form Output

5001_Ch08 07/12/01 2.29 pm Page 288

Page 21: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

// calculate number of lines per page,// using the MarginBounds.lpp = ev.MarginBounds.Height /

printFont.GetHeight(ev.Graphics);

The file is printed line by line to the printer. Lines of text are obtained using theStreamReader. The ReadLine() method reads a line of characters from the current streamand returns the data as a string to the textline variable.

Next, a new value for the ypos variable is calculated in order to know where the print-ing will occur. As you can see, this value is used directly by the DrawString() method.

// Iterate over the file, printing each line.while(counter < lpp &&

((textline=streamToPrint.ReadLine())!= null)) {ypos = topMar +

(counter *printFont.GetHeight(ev.Graphics));

ev.Graphics.DrawString(textline, printFont,Brushes.Black,leftMar, ypos,new StringFormat());

counter++;}

The DrawString() method draws the line of text, given by textline in the specifiedfont and color starting at the left margin (leftMar) and at the ypos position. The countervariable is then incremented in order that the next line is printed lower on the page.

This process continues until the page is full or until there is no more text to print.When an additional page is needed, the following code provides a new page to the printer.

// More lines? Print another pageif(textline != null)

ev.HasMorePages = true;else

ev.HasMorePages = false;}

Finally a call is made to the Dispose() method when we are finished using the twoderived classes.

public override void Dispose() {base.Dispose();components.Dispose();

}

Send It Out 289

5001_Ch08 07/12/01 2.29 pm Page 289

Page 22: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

This application prints a file to the printer that is a portion of the U.S. Constitution, asshown in Figure 8.8.

As an additional test, unplug your printer and attempt to print directly to your printeronce again. Figure 8.9 shows the error message printed to the Label2 text field.

Now, we have a question and challenge for you. First, find the following portion ofcode in the project’s listing.

ev.Graphics.DrawString(textline, printFont,Brushes.Black,leftMar, ypos,new StringFormat());

Assuming the printer is a color printer, will the printer print in a blue font if the brushcolor is changed to blue?

Using an AdRotator Control

The AdRotator control is used to display ad banners on Web pages. The AdRotator controlcan be configured in such a manner as to change the ad each time the Web page is refreshed.

290 Chapter 8 • Processing Web Form Output

Figure 8.8 A portion of the output sent to the printer.

5001_Ch08 07/12/01 2.29 pm Page 290

Page 23: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

The AdRotator control can be placed on a form by simply dragging it from the Web con-trol’s Toolbox.

The properties pane shows a variety of AdRotator properties that can be set duringdesign time. The unique AdRotator properties are described in Table 8.3.

Table 8.3 AdRotator Properties

Unique AdRotator Property Function

AdvertisementFile This is the path to a specifically formatted XML file.

KeywordFilter Provides a filter for the source of ads. When the source is given inthe AdvertisementFile property and the KeywordFilter property isset, an ad with a matching keyword is selected. When the sourceis given in the AdvertisementFile property and the KeywordFilterproperty is set but no match occurs, the AdRotator control rendersa blank image. A trace warning is then given. If the KeywordFilterproperty is empty, no filtering is used.

Target Uses one of the HTML frame keywords, including _top, _parent,_search, _self, or _blank.

Send It Out 291

Figure 8.9 An exception error message has been trapped.

5001_Ch08 07/12/01 2.30 pm Page 291

Page 24: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

The AdRotator responds, or fires, in response to an AdRotator_AdCreated event.The AdRotator uses a special XML file format for the advertisement. The format is shownin the following listing:

<?xml xmlns=”Ad Rotator Schedule” ?><Advertisements>

<Ad><ImageUrl>URL of image to display</ImageUrl><TargetUrl> URL of page to link to </TargetUrl><AlternateText>

Text to show as ToolTip</AlternateText><Keyword>keyword used to filter</Keyword><Impressions>relative weighting of ad</Impressions>

</Ad></Advertisements>

Table 8.4 provides information on these XML formatting specifications.

Table 8.4 XML Formatting Options

XML Formatting Required/Optional DescriptionOption

AlternateText optional Uses the ALT attribute of the image. This may appearas a ToolTip for the ad. The text is displayed when theImageURL is not available.

ImageUrl required Provides an absolute/relative URL to an image file.

Impressions optional Uses a number for indicating the weight of an ad. Thisaffects the ad rotation schedule. Larger numbers havea higher weight than smaller numbers. The value forall ads cannot exceed 2,048,000,000 – 1.

Keyword optional Provides a category for the ad to be used as a filter.

TargetUrl optional Provides the URL of a page to link to when the userclicks on the ad.

Our project for this section is named Ad. The XLS file uses two equally weighted ads,as shown in the following listing.

<Advertisements><Ad>

<ImageUrl>c://ad1.gif</ImageUrl><NavigateUrl>http://www.microsoft.com</NavigateUrl><AlternateText>Microsoft</AlternateText><Impressions>50</Impressions>

292 Chapter 8 • Processing Web Form Output

5001_Ch08 07/12/01 2.30 pm Page 292

Page 25: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

</Ad>

<Ad><ImageUrl>c://ad2.gif</ImageUrl><NavigateUrl>http://www.claverack.com</NavigateUrl><AlternateText>Claverack Electric Coop.</AlternateText><Impressions>50</Impressions>

</Ad></Advertisements>

The project uses only one AdRotator control placed on a Web Form, as shown in Fig-ure 8.10.

Note the AdRotator’s properties in the Properties pane of the design screen. The codefor this project is simple and straightforward since the ad information is supplied at designtime.

using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;

Send It Out 293

Figure 8.10 An AdRotator control is placed and sized on the form.

5001_Ch08 07/12/01 2.30 pm Page 293

Page 26: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;using System.IO;

namespace Ad{

/// <summary>/// Summary description for WebForm1./// </summary>public class WebForm1 : System.Web.UI.Page{

protected System.Web.UI.WebControls.AdRotatorAdRotator1;

public WebForm1(){

Page.Init += new System.EventHandler(Page_Init);}

private void Page_Load(object sender, EventArgs e){

// Put use code to initialize the page here}

private void Page_Init(object sender, EventArgs e){

//// CODEGEN: This call is required by the ASP.NET// Web Form Designer.//InitializeComponent();

}

#region Web Form Designer generated code/// <summary>/// Required method for Designer support – do/// not modify the contents of this method with/// the code editor./// </summary>private void InitializeComponent(){

this.AdRotator1.AdCreated += newSystem.Web.UI.WebControls.AdCreatedEventHandler(this.AdRotator1_AdCreated);

294 Chapter 8 • Processing Web Form Output

5001_Ch08 07/12/01 2.30 pm Page 294

Page 27: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

this.Load += new System.EventHandler(this.Page_Load);

}#endregion

private void AdRotator1_AdCreated(object sender,System.Web.UI.WebControls.AdCreatedEventArgs e)

{// no additional code required for statically// supplied URLs

}}

}

This AdRotator project will alternate between two URLs as shown in Figure 8.11 andFigure 8.12.

Other sites can be added at any time.

When you view the HTML document, you should see the following code provided forthe AdRotator.

Send It Out 295

Figure 8.11 The Microsoft Web site.

5001_Ch08 07/12/01 2.30 pm Page 295

Page 28: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

<asp:AdRotator id=AdRotator1 runat=”server” Target=”_self”Width=”589” Height=”350” advertisementfile=”Ad.xml”backcolor=”#FFC080” bordercolor=”Green”borderstyle=”Solid” borderwidth=”3px”>

Take the time to experiment with this control and format a few ads in your own XLSfile. A lot of useful information can be passed to clients using the AdRotator control.

Send It Out—In a ListIn the previous section, you learned how to send information to various controls. The infor-mation sent was usually a string or a string of information formatted in a particular manner.You learned that simple formatting techniques could provide tabular lists of data in variouscontrols.

In this section, you will learn how to incorporate various controls that are capable ofdisplaying lists on Web pages. There are essentially four types of controls designed for cre-ating lists:

• Table control

• DataGrid control

296 Chapter 8 • Processing Web Form Output

Figure 8.12 The Claverack Web site.

5001_Ch08 07/12/01 2.30 pm Page 296

Page 29: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

• DataList control

• Repeater control

Table 8.5 briefly lists each control type followed by a column of suggested uses and acolumn of advantages and capabilities.

Table 8.5 ASP.NET Controls for Displaying Lists

Control Use Advantages/Capabilities

DataGrid Provides a full-featured list The appearance of the table can be customized. A output with editing capabilities. grid appearance is the default. Autoformatting is

possible with output using a variety of options,including bound columns, columns of buttons orhyperlinks, and custom columns created usingtemplates. Provides support for single and multipleselections.

No separator template is required. The contentscan be edited, sorted, and deleted.

DataList Provides easy customizable The appearance of the table can be customized.list output with editing. This includes autoformatting. List items support

styles that can provide a unique look. Separatorsbetween individual elements can use templates.

Provides support for single and multiple selections.The layout supports columns or rows, with multiplecolumns an option.

All data in this control is displayed in a single list.

Repeater Provides simple, read-only The appearance of a Repeater control is governed list output. by the use of templates, therefore there is no inher-

ent look for this control. No support is provided forselection or editing since this is a read-only control.Separators between individual elements can usetemplates.

All data in this control is displayed in a single list.

Table Provides list output in a simple This control is unique in that it is not data-bound.programmable table format. It can be used to display various combinations of

HTML text and HTML controls. The Table controldoes not use templates. Rows are created withTableRow controls and cells with TableCell controls.

In the following sections, we’ll examine Table, DataGrid, DataList, and Repeater con-trols in more detail and provide you with a simple application for each type. The applica-tions we have provided are modifications of examples provided with Microsoft SDK.

Send It Out—In a List 297

5001_Ch08 07/12/01 2.30 pm Page 297

Page 30: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

Using Table Controls

The Table Web server control is used to create server-programmable tables on a Web Formspage. By using the TableRow and TableCell server controls, the content of the Table controlcan be displayed.

Table controls are usually used as a way to present tabular information and as a wayto format information on a Web page. The Table control is usually used when it is desirableto add rows and columns at runtime.

The Table control accomplishes many of the same feats as the other list controls(DataGrid, DataList, and Repeater). The basic difference is that the three list controls aredata bound and work against a data source. Table controls, on the other hand, are not neces-sarily data bound and can display any combinations of text and controls.

The Table control does not use templates, as do the other list controls, but relies on theTableCell and TableRow controls. For example, Table controls have a Rows property that isa collection of TableRow objects. The TableRow control supports a collection called Cellsmade up of TableCell objects. The TableCell control is then used to display a given cell.

The application for this section is named TblCtrl. The following code listing is thecomplete code required for this project. First, create a new C# project for the Web namedTblCtrl. From the Design View pane, switch to the HTML View pane and enter the follow-ing code.

<html><head><script language=C# runat=”server”>

void Page_Load(Object sender, EventArgs e) {

int numcells = int.Parse(DropDown1.SelectedItem.Value);int numrows = int.Parse(DropDown2.SelectedItem.Value);string tempstr = “”;

// Generate rows and columnsfor (int j = 0; j < numrows; j++) {

TableRow tr = new TableRow();for (int i = 0; i < numcells; i++) {

if (i == 0) tempstr = “A”;else if (i == 1) tempstr = “B”;else if (i == 2) tempstr = “C”;else if (i == 3) tempstr = “D”;else if (i == 4) tempstr = “E”;else if (i == 5) tempstr = “F”;else if (i == 6) tempstr = “G”;else if (i == 7) tempstr = “H”;

298 Chapter 8 • Processing Web Form Output

5001_Ch08 07/12/01 2.30 pm Page 298

Page 31: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

TableCell tc = new TableCell();tc.Controls.Add(new LiteralControl

(tempstr + (j + 1).ToString()));

tr.Cells.Add(tc);}Table1.Rows.Add(tr);

}}

</script>

</HEAD><body><h3><font face=Arial>Using Table Web Controls </FONT></H3><form id=Form1 runat=”server”><asp:table id=Table1 runat=”server” Gridlines=”Both”

BorderWidth=”2” BorderColor=”black”CellSpacing=”0” CellPadding=”5”Font-Size=”10pt” Font-Name=”Arial”></asp:Table>

<p><br>Number of Columns:<asp:dropdownlist id=DropDown1 runat=”server”>

<asp:ListItem Value=”1”>A</asp:ListItem><asp:ListItem Value=”2”>B</asp:ListItem><asp:ListItem Value=”3”>C</asp:ListItem><asp:ListItem Value=”4”>D</asp:ListItem><asp:ListItem Value=”5”>E</asp:ListItem><asp:ListItem Value=”6”>F</asp:ListItem><asp:ListItem Value=”7”>G</asp:ListItem><asp:ListItem Value=”8”>H</asp:ListItem>

</asp:DropDownList><br><br>Number of Rows:<asp:dropdownlist id=DropDown2 runat=”server”>

<asp:ListItem Value=”1”>1</asp:ListItem><asp:ListItem Value=”2”>2</asp:ListItem><asp:ListItem Value=”3”>3</asp:ListItem><asp:ListItem Value=”4”>4</asp:ListItem><asp:ListItem Value=”5”>5</asp:ListItem><asp:ListItem Value=”6”>6</asp:ListItem><asp:ListItem Value=”7”>7</asp:ListItem><asp:ListItem Value=”8”>8</asp:ListItem>

</asp:DropDownList><p><asp:button id=Button1 runat=”server” Text=”Push to generate the table”></asp:button></FORM></P>

</body></HTML>

Send It Out—In a List 299

5001_Ch08 07/12/01 2.30 pm Page 299

Page 32: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

Once you have entered the code, build and test the application in the normal manner.

Figure 8.13 shows the control placement and Properties pane while in Design mode.

When the project is executed, you’ll see how the project will generate a table wherethe user can specify the number of columns and rows.

Figure 8.14 shows the TblCtrl project during execution with four columns and threerows.

The cell data for the TblCtrl project gives cell data as it might be specified in a spread-sheet.

Using DataGrid Controls

The DataGrid Web server control is used to display tabular data on a Web form. The controlsupports selecting, editing, sorting, and paging for the bound data. This control is bound toa data source using the DataSource property in order for it to be rendered on the Web page.The data source can be a class that supports the ICollection interface. The DataGrid con-trol’s grid then displays one row for every row in the data source. The control creates abound column for each field in the data source, but which field generates a column in thegrid can be specified.

300 Chapter 8 • Processing Web Form Output

Figure 8.13 Control placement for the TblCtrl project.

5001_Ch08 07/12/01 2.30 pm Page 300

Page 33: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

The DataBind method is used to gather data for the grid. Grid columns are generatedautomatically based on fields in the data source but can be manipulated via bound columns,hyperlinks, button controls, Edit command columns, Template columns, and so on. Formore details, use the Visual Studio.NET Help facility on this topic.

Sorting data is not directly supported, but allows you to add sort options to the grid.One technique is to use link buttons as column heads. Then, when the user clicks on a linkbutton, a sort notification is raised.

In the application in this section, named DGCtrl, a DataGrid is used that will producea three column and nine row grid.

To create this project, start a new C# Web project named DGCtrl and enter the follow-ing code while in the HTML Design pane.

<%@ Import Namespace=”System.Data” %><html><head><script language=C# id=Script1 runat=”server”>

ICollection CreateDataSource() {DataTable dt = new DataTable();DataRow dr;

Send It Out—In a List 301

Figure 8.14 The TblCtrl project during execution.

5001_Ch08 07/12/01 2.30 pm Page 301

Page 34: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

DateTime nowdt;nowdt = DateTime.Now;

// Create a DataGrid with three columnsdt.Columns.Add(new DataColumn(“Item #”, typeof(Int32)));dt.Columns.Add(new DataColumn(“Date/Time Component”,

typeof(string)));dt.Columns.Add(new DataColumn(“Value”, typeof(Int32)));

// Add Row information for Yeardr = dt.NewRow();dr[0] = 1;dr[1] = “Year”;dr[2] = nowdt.Year;dt.Rows.Add(dr);

// Add Row information for Monthdr = dt.NewRow();dr[0] = 2;dr[1] = “Month”;dr[2] = nowdt.Month;dt.Rows.Add(dr);

// Add Row information for Daydr = dt.NewRow();dr[0] = 3;dr[1] = “Day”;dr[2] = nowdt.Day;dt.Rows.Add(dr);

// Add Row information for Day of Yeardr = dt.NewRow();dr[0] = 4;dr[1] = “Day of Year”;dr[2] = nowdt.DayOfYear;dt.Rows.Add(dr);

// Add Row information for DayOfWeekdr = dt.NewRow();dr[0] = 5;dr[1] = “Day of Week”;dr[2] = nowdt.DayOfWeek;dt.Rows.Add(dr);

// Add Row information for Hourdr = dt.NewRow();dr[0] = 6;

302 Chapter 8 • Processing Web Form Output

5001_Ch08 07/12/01 2.30 pm Page 302

Page 35: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

dr[1] = “Hour”;dr[2] = nowdt.Hour;dt.Rows.Add(dr);

// Add Row information for Minutesdr = dt.NewRow();dr[0] = 7;dr[1] = “Minutes”;dr[2] = nowdt.Minute;dt.Rows.Add(dr);

// Add Row information for Secondsdr = dt.NewRow();dr[0] = 8;dr[1] = “Seconds”;dr[2] = nowdt.Second;dt.Rows.Add(dr);

// Add Row information for Millisecondsdr = dt.NewRow();dr[0] = 9;dr[1] = “Milliseconds”;dr[2] = nowdt.Millisecond;dt.Rows.Add(dr);

DataView dv = new DataView(dt);return dv;

}

void Page_Load(Object sender, EventArgs e) {MyDataGrid.DataSource = CreateDataSource();MyDataGrid.DataBind();

}

</script></head><body><h3><font face=Arial>Using the DataGrid Web Control</FONT></H3><h3><font face=Arial color=green>Current Date &amp; TimeInformation</FONT></H3>

<form runat=server ID=Form1>

<ASP:DataGrid id=”MyDataGrid” runat=”server”BorderColor=”Blue”BorderWidth=”1”

Send It Out—In a List 303

5001_Ch08 07/12/01 2.30 pm Page 303

Page 36: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

GridLines=”Both”CellPadding=”3”CellSpacing=”0”Font-Name=”Arial”Font-Size=”Medium”HeaderStyle-BackColor=”#aaaadd”backcolor=”#C0FFC0”font-names=”Arial”/>

</form>

</body></html>

It is easy to see how each column and row is added to the DataGrid control by exam-ining this code. The cells of the control are filled with both string and integer data.

Figure 8.15 shows the placement of the controls when you switch back to the Designpane.

Figure 8.16 shows the execution of the application.

The output for the DGCtrl project is a well-formatted grid showing an item number,text string, and data value for date and time information returned by the system.

304 Chapter 8 • Processing Web Form Output

Figure 8.15 Placement of controls for the DGCtrl project.

5001_Ch08 07/12/01 2.30 pm Page 304

Page 37: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

Using DataList Controls

The DataList Web control is used to display database information. The control provides theadvantage of being able to format this data by using templates and styles. The DataList con-trol is useful for displaying rows of database information as items in the list. The layout ofthe items is governed by using HTML text and controls.

The DataList control, like the DataGrid control, is bound to a data source. This con-trol also uses any data source class that supports the ICollection interface. The DataListcontrol uses templates to specify the layout. Table 8.6 provides a list and description ofDataList templates.

The application for this section is named DLCtrl. To create this project, open a newC# Web project named DLCtrl. From the HTML tab of the Designer pane, enter the codeshown in the following listing.

<%@ Import Namespace=”System.Data” %>

<HTML><script language = “C#” runat=”server”>

ICollection CreateDataSource()

Send It Out—In a List 305

Figure 8.16 Output from the DGCtrl project.

5001_Ch08 07/12/01 2.30 pm Page 305

Page 38: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

{DataTable dt = new DataTable();DataRow dr;

dt.Columns.Add(new DataColumn(“StringValue”,typeof(string)));

for (int i = 0; i < 21; i++) {

dr = dt.NewRow();dr[0] = “Cell “ + (i + 1).ToString();dt.Rows.Add(dr);

}

DataView dv = new DataView(dt);return dv;

}

void Page_Load(Object sender, EventArgs e) {

if (!IsPostBack) {

DataList1.DataSource = CreateDataSource();DataList1.DataBind();

}}

306 Chapter 8 • Processing Web Form Output

Table 8.6 DataList Control Templates

Template Option Description

AlternatingItemTemplate Similar to the ItemTemplate element. Renders every other row in theDataList control. Typically used to shade alternate cells in a differentcolor.

EditItemTemplate Specifies the layout of an item when it is in edit mode. Provides edit-ing controls.

HeaderTemplate/ Specifies the text and controls that will be rendered at the start andFooterTemplate end of the list.

ItemTemplate Specifies the HTML elements and controls that are rendered foreach row in the data source.

SelectedItemTemplate Specifies the HTML elements that are rendered when an item isselected from the DataList control. A switch in background or fore-ground color is typical.

SeparatorTemplate Specifies the elements that are rendered between each item.

5001_Ch08 07/12/01 2.30 pm Page 306

Page 39: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

void Button1_Click(Object sender, EventArgs e) {

DataList1.RepeatDirection = RepeatDirection.Horizontal;

if (DropDown1.SelectedIndex == 0)DataList1.RepeatLayout = RepeatLayout.Table;

elseDataList1.RepeatLayout = RepeatLayout.Flow;

DataList1.RepeatColumns=DropDown2.SelectedIndex+1;

DataList1.BorderWidth = Unit.Pixel(1);DataList1.GridLines = GridLines.Both;

}

</script>

<body>

<form runat=server>

<h3><font face=”Arial”>Using A DataList Control</font></h3>

<asp:DataList id=”DataList1” runat=”server”BorderColor=”black”CellPadding=”3”Font-Name=”Arial”Font-Size=”8pt”>

<HeaderStyle BackColor=”#aaaadd”></HeaderStyle>

<ItemStyle BackColor=”Gainsboro”></ItemStyle>

<HeaderTemplate>

Cell Item #

</HeaderTemplate>

<ItemTemplate>

<%# DataBinder.Eval(Container.DataItem,“StringValue”) %>

Send It Out—In a List 307

5001_Ch08 07/12/01 2.30 pm Page 307

Page 40: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

</ItemTemplate>

</asp:DataList>

<p><hr noshade align=”left” width=”300”>

<br>

RepeatLayout:

<asp:DropDownList id=DropDown1 runat=”server”><asp:ListItem Value=”Table Format”>Table Format</asp:ListItem><asp:ListItem Value=”Flow Format”>Flow Format</asp:ListItem>

</asp:DropDownList><br>

RepeatColumns:

<asp:DropDownList id=DropDown2 runat=”server”><asp:ListItem Value=”1”>1</asp:ListItem><asp:ListItem Value=”2”>2</asp:ListItem><asp:ListItem Value=”3”>3</asp:ListItem><asp:ListItem Value=”4”>4</asp:ListItem><asp:ListItem Value=”5”>5</asp:ListItem><asp:ListItem Value=”6”>6</asp:ListItem><asp:ListItem Value=”7”>7</asp:ListItem><asp:ListItem Value=”8”>8</asp:ListItem><asp:ListItem Value=”9”>9</asp:ListItem><asp:ListItem Value=”10”>10</asp:ListItem>

</asp:DropDownList><br>

<asp:LinkButton id=Button1 Text=”Refresh DataList” OnClick=”Button1_Click” runat=”server”/>

</form>

</body></HTML>

This application creates a table or flow format for the data. The cell placement is hori-zontal. This means the cells will be placed sequentially in the horizontal direction until

308 Chapter 8 • Processing Web Form Output

5001_Ch08 07/12/01 2.30 pm Page 308

Page 41: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

filled. The actual placement of cell information is dependent upon the number of columnsused in the DataList control.

Figure 8.17 shows the placement of the project’s controls.

When the application is executed, your screen should be similar to Figure 8.18.

Experiment with this application and note the results for the previous conditions whena flow layout is selected.

Using Repeater Controls

The Repeater Web server control is used to create custom lists from any available data. Unlikethe DataGrid and DataList controls, the Repeater control does not have an inherent look. Thelayout of the Repeater control is controlled by templates. When the Web page runs, theRepeater control loops through the data source records and renders an item for each record.

Since the Repeater control’s layout is controlled by templates, it can be used to gener-ate a bulleted list, numbered list, comma delimited list, a table or grid, and more.

The templates that control the layout can contain combinations of HTML text andcontrols. See Table 8.6, shown earlier, for a list and description of template types supportedby the Repeater control.

Send It Out—In a List 309

Figure 8.17 Control placement in the DLCtrl project.

5001_Ch08 07/12/01 2.30 pm Page 309

Page 42: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

The Repeater control, like the DataGrid and DataList controls, must be bound to adata source using the DataSource property. Also, like the DataGrid and DataList controls,this control can use any data source class that supports the ICollection interface. In addition,the Repeater control supports the IEnumerable interface.

The Repeater control supports two events: ItemCreated and ItemCommand. The Item-Created event allows customization of the item creation process. The ItemCommand eventfires when an individual item is selected with a button click.

The application for this section is named RepCtrl. To create this application, start anew C# Web project and name it RepCtrl. From the HTML tab of the Design pane, enter thefollowing project code.

<html><head><script language=”C#” runat=”server” ID=Script1>

void Page_Load(Object Sender, EventArgs e) {

if (!IsPostBack) {

ArrayList values = new ArrayList();

310 Chapter 8 • Processing Web Form Output

Figure 8.18 Execution of the DLCtrl project.

5001_Ch08 07/12/01 2.30 pm Page 310

Page 43: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

values.Add(new PositionData(“William Beston”,“Dean of Technology (retired)”));

values.Add(new PositionData(“Shannon Covert”,“CST - Full Time Adjunct”));

values.Add(new PositionData(“Donald Dellow”,“President - Broome Community College”));

values.Add(new PositionData(“Alan Dixon”,“EET - Professor (retired)”));

values.Add(new PositionData(“Mort Goldberg”,“Math - Professor (retired)”));

values.Add(new PositionData(“Rachel Hinton”,“CST - Assistant Professor”));

values.Add(new PositionData(“Gary Kohut”,“CST - Technician”));

values.Add(new PositionData(“Ken Mansfield”,“CST - Associate Professor”));

values.Add(new PositionData(“Beth Mollen”,“CST - Associate Professor”));

values.Add(new PositionData(“William Murray”,“EET - Department Chair”));

values.Add(new PositionData(“Chris Pappas”,“CST - Department Chair”));

values.Add(new PositionData(“Julie Peacock”,“Dean of Technology”));

values.Add(new PositionData(“Lydia Smith”,“CST / EET Department Secretary”));

Repeater1.DataSource = values;Repeater1.DataBind();

Repeater2.DataSource = values;Repeater2.DataBind();

}}

public class PositionData {

private string name;private string position;

public PositionData(string name, string position) {this.name = name;this.position = position;

}

public string Name {get {

Send It Out—In a List 311

5001_Ch08 07/12/01 2.30 pm Page 311

Page 44: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

return name;}

}

public string Position {get {

return position;}

}}

</script>

</head><body>

<h3><font face=”Arial” color=bluesize=12>Using Repeater Web Controls</font></h3>

<form runat=server ID=Form1>

<b>From Repeater Control #1:</b>

<p>

<asp:Repeater id=Repeater1 runat=”server”>

<HeaderTemplate>

<table border=1><tr><td><b>Employee Name</b></td><td><b>Employee Position</b></td>

</tr>

</HeaderTemplate>

<ItemTemplate>

<tr><td> <%# DataBinder.Eval(Container.DataItem,

“Name”) %> </td><td> <%# DataBinder.Eval(Container.DataItem,

“Position”) %> </td></tr>

</ItemTemplate>

312 Chapter 8 • Processing Web Form Output

5001_Ch08 07/12/01 2.30 pm Page 312

Page 45: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

<FooterTemplate>

</table>

</FooterTemplate>

</asp:Repeater>

<p>

<b>From Repeater Control #2:</b>

<p>

<asp:Repeater id=Repeater2 runat=”server”>

<HeaderTemplate>Broome Community College data:

</HeaderTemplate>

<ItemTemplate><%# DataBinder.Eval(Container.DataItem,

“Name”) %>[<%# DataBinder.Eval(Container.DataItem,

“Position”) %>]</ItemTemplate>

<SeparatorTemplate>,</SeparatorTemplate>

</asp:Repeater>

<asp:Repeater id=Repeater3 runat=”server”></asp:Repeater>

</form></P>

</body></html>

As you study this code, you will notice the use of several templates for the layout ofthe Repeater control’s data.

Also note that two Repeater controls are used. The first renders the data in a table for-mat while the second control renders the data in a flow format using comma delimiters.

Figure 8.19 shows the layout of the controls in Design mode once the previous codeis entered in the HTML pane.

Figure 8.20 shows the output from the RepCtrl project.

Send It Out—In a List 313

5001_Ch08 07/12/01 2.30 pm Page 313

Page 46: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

314 Chapter 8 • Processing Web Form Output

Figure 8.19 Control placement for the RepCtrl project.

Figure 8.20 Data is rendered differently using two Repeater controls.

5001_Ch08 07/12/01 2.30 pm Page 314

Page 47: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

You’ll have to agree that the Repeater control provides the most flexibility in render-ing list data.

SummaryIn future chapters, you will see additional examples of formatting numeric, date, and timedata as the need arises.

In this chapter, you have gleaned how large a topic data output can be. We’ll continuebuilding upon the material presented in this chapter throughout the remainder of the book.

Summary 315

5001_Ch08 07/12/01 2.30 pm Page 315

Page 48: Processing Web Form Output T - Pearson EducationYou have heard the saying “One picture is worth a thousand words.” An application’s screen and printer output can say just as

5001_Ch08 07/12/01 2.30 pm Page 316