ASP.NET (Newer Series)

Data Reading and Formatting

After a user has finished preparing values in a form, he or she can send them to you. To allow you to get values from the user, the IIS's own library…

19 min read4,117 words9 code samples

A Request From a Form#

Introduction#

After a user has finished preparing values in a form, he or she can send them to you. To allow you to get values from the user, the IIS's own library provides an object called Request. When a form is created on a web page, that form becomes a property of the Request object. The objects that are part of the form constitute a collection and each object of the form becomes a member of this collection. To access an object of this collection, you can use Request.Form() (this can be referred to as an indexed property because each object can be accessed using its index). For example, you can enter the name of a control between double-quotes in the parentheses of Request.Form(). If you use Request.Form() to access a control, the information should be collected using the POST value of the METHOD attribute of the form. Based on this, to access any control on the form, you would type:

C#
Request.Form(Object).OptionalIndex.Count

The object you need to access can be entered as the Object part. For example, you can enter the name of a form's control as "Object". This can be done as follows:

C#
Request.Form("txtFirstName")

In our lessons about arrays and collections, we will review what roles the OptionalIndex factor and the Count value play. For now, we will ignore them.

A String Request#

Besides, or as opposed to, collecting values using the controls on a form, you can request a string. To support this, the Request object is equipped with QueryString, which also is a collection. This allows you to get values either from a control or directly from the address bar of the browser. Remember, the GET value of the METHOD attribute of a form causes its information to be displayed in the address bar of the browser when that information is being sent:

Notice that the section on the right side of the question mark includes parts using the formula Name=Value. This indicates that the section on the right side of the question mark is in fact a collection of strings. Each string in this collection can be produced to you by Request.QueryString. The syntax of Request.QueryString is:

C#
Request.QueryString(Variable).OptionalIndex.Count

The Variable parameter is the name of the string that you want to retrieve. It can be the name of a control passed as argument. Here is an example:

C#
Request.QueryString("txtFirstName")

It can also be the name of a variable. In our lessons about arrays and collections, we will review what roles the OptionalIndex factor and the Count value play. This also means that, as opposed to the Request.Form collection that uses the POST value of the method attribute of a form, when using the Request.QueryString property, you should send values using GET.

HTML Encoding#

Introduction#

Although most web pages are meant only to display values, some others, mostly interactive pages, allow a visitor to submit values. To do this, a visitor may type in a text box, select a radio button, or click a check box. These actions create a value on the browser. The browser is referred to as a client because this is where the visitor creates a value. After formulating a value, a user would click a button to send the value to you. You get that value on the server. To assist you with getting a value from a browser, the .NET Framework provides a class named HttpUtility.

Encoding a Value#

When a web page visitor types a value or selects from a control, the value must be analyzed and made into a readable type. To make this possible, the value must be encoded. To support this operation, the HttpUtility class is equipped with a method named HtmlEncode. The value must be passed in the parentheses of HttpUtility.HtmlEncode(). This value would be the one you get from a call to Request.QueryString(ControlName). This means that you can pass the Request.QueryString(ControlName) expression to the HttpUtility.HtmlEncode() call. This would be done as follows:

C#
<%@ Page Language="C#" %>
<html>
<head>

<style>

body {
    font-family: Verdana, Helvetica, Arial, 'Sans Serif';
    color: #000000;	
    font-size: 10pt;
    background-color: #FFFFFF }

hr { color=#000080 }

.toptitle {
  color: #000080;
  font-family: 'Times New Roman', Garamond, Georgia, Serif;
  text-align: center;
  font-size: 24pt;
  font-weight: bold;
  text-decoration: none }

.housetitle {
  color: #0000FF;
  font-family: Georgia, Times New Roman, Courier New;
  font-size: 16pt;
  font-weight: bold;
  text-decoration: none }

.names {
  font-family: Verdana;
  font-size: 10pt }

</style>

<title>Grier Summer Camp</title>
</head>
<body>

<p class='toptitle'>Grier Summer Camp</p>

<p class='housetitle'>Registration</p>

<p>Please use this form to register.</p>

<form action="index.aspx" method="get">
 <table border="0" width="320">
    <tr>
      <td width="100" class="names">First Name:</td>
      <td>
	<input type="text" name="txtFirstName" size="10"
          value="<%=HttpUtility.HtmlEncode(Request.QueryString["txtFirstName"])%>">
      </td>
    </tr>
    <tr>
      <td width="100" class="names">Last Name:</td>
      <td>
	<input type="text" name="txtLastName" size="10"
          value="<%=HttpUtility.HtmlEncode(Request.QueryString["txtLastName"])%>">
      </td>
    </tr>
    <tr>
      <td width="100" valign="top" class="names">Full Name:</td>
      <td>
	<input type="text"
	       name="txtFullName"
               size="21"
	  value="<%=HttpUtility.HtmlEncode(Request.QueryString["txtFirstName"]) +
	    " " + 
	    HttpUtility.HtmlEncode(Request.QueryString["txtLastName"])%>">
        <input type="submit" value="Submit it">
      </td>
    </tr>
  </table>
</form>

<table border="0" width="100%" cellspacing="0" cellpadding="0">
  <tr>
    <td width="100%">
      <hr color="#FF0000">
    </td>
  </tr>
  <tr>
    <td width="100%"
        align="center"
        style="font-family: Verdana; font-size: 10pt">
		Copyright © 2009 Grier Summer Camp
    </td>
  </tr>
</table>

</body>
</html>

Using Values in HTML and JavaScript#

Introduction#

As you may know by now, before ASP.NET, there was HTML, then JavaScript. HTML was created with its own set of controls to anticipate a value-based interaction between a visitor and a web page. But HTML is not equipped to process its own web controls. This is done using JavaScript. Before using JavaScript to process values created by a visitor, of course, you must first create a form and populate it with the necessary controls. Practical Learning: Introducing Web Controls

  1. Start Microsoft Visual Web Developer or Microsoft Visual Studio
  2. Create a web site and name it geometry2
  3. In the Solution Explorer, right-click Default.aspx and click Rename
  4. Type index.aspx and press Enter
  5. While the code file is opened, change the name of the form from form1 to frmGeometry <%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title> Geometry Tutorials </title> </head> <body> <h2>Geometry Tutorials</h2> <form id=" frmGeometry " runat="server"> <div> </div> </form> </body> </html>
  6. Click the Design button
  7. Click the box under the Geometry line
  8. On the main menu, click Table -> Insert Table
  9. Set the characteristics as follows: Rows: 1 Columns: 3 Width: 300 In Pixels
  10. Click OK
  11. To create a new web page, on the main menu, click Website -> Add New Item...
  12. Click Web Form. Replace the name as circle (you don't have to provide an extension)
  13. Click Add
  14. While the code file is still opened, change the name of the form from form1 to frmCircle <%@ Page Language="C#" AutoEventWireup="true" CodeFile="circle.aspx.cs" Inherits="circle" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title> Geometry - Circle </title> </head> <body> <h2>Geometry - Circle</h2> <form id=" frmCircle " runat="server"> <div> </div> </form> </body> </html>
  15. Click the Design button
  16. Click the box under the Geometry - Circle line
  17. On the main menu, click Table -> Insert Table
  18. Set the characteristics as follows: Rows: 4 Columns: 3 Width: 400 In Pixels
  19. Click OK
  20. Click the top-left empty cell of the table and type Radius:
  21. Press the down arrow key and type Diameter:
  22. Press the down arrow key and type Circumference:
  23. Press the down array key and type Area:
  24. On the Toolbox, expand the HTML section
  25. Drag Input (Text) and drop it in the middle-top cell of the table
  26. While the text box is still selected, in the Properties window, click (Id) and type txtRadius
  27. Click Value and type 0.00
  28. From the Toolbox, drag Input (Text) and drop it in the middle-center empty cell of table
  29. While the text box is still selected, in the Properties window, click (Id) and type txtDiameter
  30. From the Toolbox, drag Input (Text) and drop it in the middle-center empty cell of table
  31. While the text box is still selected, in the Properties window, click (Id) and type txtCircumference
  32. From the Toolbox, drag Input (Text) and drop it in the middle-bottom empty cell of table
  33. While the text box is still selected, in the Properties window, click (Id) and type txtArea
  34. Save all
  35. From the HTML section of the Toolbox, drag Input (Button) and drop it in the top-right empty cell of table
  36. While the button is still selected, in the Properties window, click (Id) and type btnCalculate
  37. Click Value and type Calculate
  38. Save the file

Processing Values in JavaScript#

To process the values submitted by a visitor of an HTML or ASP web page, you must write code in JavaScript. This code consists of one or more JavaScript functions. To manually do this, in the head section of the file that contains the control(s), start a section with <script language="javascript" type="text/javascript"> and close it with </script>:

C#
<script language="javascript" type="text/javascript">

</script>

Between these two lines, enter the necessary code, which is mainly made of functions. After creating the function, if it will be processed from clicking a button, in the form, locate that button and assign it the name of the function preceded by return. This must be assigned as a string. To get assistance from Microsoft Visual Web Developer or Microsoft Visual Studio, after creating a form, double-click the button. The programming environment would automatically create the sectional code in the head section, provide skeleton code for a function, and assign the name of that function to the button on the form. Practical Learning: Processing Values With JavaScript

  1. On the form, double-click the Calculate button
  2. Implement the function as follows: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="circle.aspx.cs" Inherits="circle" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <style type="text/css"> .maintable { width: 400px; } .labelscolumn { width: 100px; } .midcolumn { width: 120px; } #btnCalculate { width: 120px; } </style> <title>Geometry - Circle</title> <script language="javascript" type="text/javascript"> // <!CDATA[ function btnCalculate_onclick() { var dblRadius; var dblDiameter, dblCircumference, dblArea; dblRadius = frmCircle.txtRadius.value; dblDiameter = dblRadius * 2; dblCircumference = dblDiameter * 3.14159; dblArea = dblRadius * dblRadius * 3.14159; frmCircle.txtDiameter.value = dblDiameter; frmCircle.txtCircumference.value = dblCircumference; frmCircle.txtArea.value = dblArea; } // ]]> </script> </head> <body> <h2>Geometry - Circle</h2> <form id="frmCircle" runat="server"> <div> <table class="maintable"> <tr> <td>Radius:</td> <td> <input id="txtRadius" type="text" value="0.00" /></td> <td> <input id="btnCalculate" type="button" value="Calculate" onclick="return btnCalculate_onclick()" /></td> </tr> <tr> <td>Diameter:</td> <td> <input id="txtDiameter" type="text" /></td> <td> </td> </tr> <tr> <td>Circumference:</td> <td> <input id="txtCircumference" type="text" /></td> <td> </td> </tr> <tr> <td>Area:</td> <td> <input id="txtArea" type="text" /></td> <td> </td> </tr> </table> </div> </form> </body> </html>
  3. Click the index.aspx tab and click the Source button
  4. In the head section of the code, type the following: <script type="text/javascript"> function ShowCircle() { javascript:window.open("circle.aspx"); } </script>
  5. Click the Design button
  6. From the Standard section of the Toolbox, drag LinkButton and drop it in left empty cell of the table of the from
  7. While the link button is selected, in the Properties window, change the following characteristics: (ID): lbCircle OnClientClick: ShowCircle() Text: Circle
  8. Execute the application to see the result
  9. Click the Circle link
  10. Enter a value in the Radius text box and click the Calculate button
  11. Close the Circle web page

Data Reading in ASP.NET#

Introduction#

When interacting with a web page, if it contains a web form that requests some values, the user may be asked to enter them in the available controls. Consider the following web page:

In this case, a visitor is expected to provide the length and the height of a rectangle. The visitor would then submit those values to you so you can calculate the perimeter and the area. Practical Learning: Introducing Data Reading

  1. In the Solution Explorer, right-click C:\...\geometry2\ and click New Folder
  2. Type images as the name of the new folder and press Enter
  3. Copy each of the following pictures to your My Documents folder:
  4. On the main menu, click Website -> Add Existing Item...
  5. Locate the folder where you saved the pictures, select each and press Enter
  6. To create a CSS file, on the main menu, click Website -> Add New Item...
  7. In the Templates list, click Style Sheet
  8. Set the name to geometry and press Enter
  9. Enter the following code in the file: body { font-size: 11pt; color: black; font-family: Verdana, Tahoma, Arial, Sans-Serif; } hr { color: #0000ff } .maintitle { color: blue; font-family: 'Times New Roman' , Garamond, Georgia, Serif; text-align: center; font-size: 24pt; font-weight: bold; text-decoration: none; } .parajust { font-family: Verdana, Tahoma, Arial, Sans-Serif; font-size: 10pt; font-weight: normal; text-align: justify; } .centeredtext { font-family: Verdana, Tahoma, Arial, Sans-Serif; font-size: 10pt; font-weight: normal; text-align: center; } .centered { text-align: center; } .formula { font-weight: bold; font-size: 10pt; color: blue; font-family: Verdana, Helvetica, Tahoma, Sans-Serif; } a:link { font-family: Verdana, Helvetica, Arial, Sans Serif; color: #0000FF; font-size: 10pt; font-weight: bold; text-decoration: none } a:alink { font-family: Verdana, Helvetica, Arial, Sans Serif; color: #FF00FF; font-size: 10pt; font-weight: bold; text-decoration: none } a:visited { font-family: Verdana, Helvetica, Arial, Sans Serif; color: Green; font-size: 10pt; font-weight: bold; text-decoration: none; } a:hover { font-family: Verdana, Helvetica, Arial, Sans Serif; color: #FF0000; font-size: 10pt; font-weight: Bold; text-decoration: none; }
  10. To add a new web page, on the main menu, click Website -> Add New Item...
  11. Make sure Web Form is selected. Set the Name to rectangle and click Add
  12. Change the file as follows: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="rectangle.aspx.cs" Inherits="rectangle" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <link rel="Stylesheet" type="text/css" href="geometry.css" /> <title> Geometry: Rectangle </title> </head> <body> <form id=" frmRectangle " runat="server" method="get" action="rectangle.aspx" > <div> <table border="0" style="width: 660px"> <tr> <td style="width: 100%"> <p class="maintitle">Geometry: Rectangle</p> </td> </tr> </table>   <table border="0" width="660"> <tr> <td> <p class="parajust">A rectangle is a geometric figure made of 4 sides connected to produce four right angles. The horizontal measurement of the rectangle, the base, is its length. The vertical measurement of the figure is referred to as its height. In geometry, a rectangle can be represented as follows:</p> <p class="centered"> <img src="images/rectangle1.gif" alt="Rectangle" /> </p> <p class="parajust">To process a rectangle, you usually must provide, or must be given, the length and the height. You can then calculate the perimeter and the area. To assist you with these calculations, you can use some pre-established formulas. Suppose the values are represented as follows:</p> </td> </tr> </table>   <table style="width: 660px"> <tr> <td style="width: 660px"> <strong>L: length</strong> </td> </tr> <tr> <td style="width: 660px"> <strong>H: height</strong> </td> </tr> <tr> <td style="width: 660px"> <strong>P: perimeter</strong> </td> </tr> <tr> <td style="width: 660px"> <strong>A: area</strong> </td> </tr> </table>   <table border="0" style="width: 660px"> <tr> <td style="width: 100%"> <p class="parajust">Based on these, the following calculations can be made</p> </td> </tr> <tr> <td style="width: 100%"> <p class="formula">P = (L + H) * 2</p> </td> </tr> <tr> <td style="width: 100%"> <p class="formula">A = L * H</p> </td> </tr> </table> <hr /> <table> <tr> <td style="width: 100px"> <asp:Label ID="Label1" runat="server" Text="Length:"> </asp:Label></td> <td style="width: 121px"> <asp:TextBox ID="txtLength" runat="server"> </asp:TextBox></td> <td style="width: 100px"> </td> </tr> <tr> <td style="width: 100px"> <asp:Label ID="Label2" runat="server" Text="Height:"> </asp:Label></td> <td style="width: 121px"> <asp:TextBox ID="txtHeight" runat="server"> </asp:TextBox></td> <td style="width: 100px"> <asp:Button ID="btnCalculate" runat="server" Text="Calculate" /></td> </tr> <tr> <td style="width: 100px"> <asp:Label ID="Label3" runat="server" Text="Perimeter:"> </asp:Label></td> <td style="width: 121px"> <asp:TextBox ID="txtPerimeter" runat="server"> </asp:TextBox></td> <td style="width: 100px"> </td> </tr> <tr> <td style="width: 100px"> <asp:Label ID="Label4" runat="server" Text="Area:"> </asp:Label></td> <td style="width: 121px"> <asp:TextBox ID="txtArea" runat="server"> </asp:TextBox></td> <td style="width: 100px"> </td> </tr> </table> <table border="0" width="660"> <tr> <td colspan="2"> <hr />  </td> </tr> <tr> <td align="center" style="height: 18px"> <a href="index.aspx">Home</a> </td> <td align="center" style="height: 18px"> <p class="centered">Copyright © 2009 NetConsulting, Inc.</p> </td> </tr> <tr> <td colspan="2"> <hr /> </td> </tr> </table> </div> </form> </body> </html>
  13. To add a new web page, on the main menu, click Website -> Add New Item...
  14. Make sure Web Form is selected. Set the Name to square
  15. Click Add
  16. Change the file as follows: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="square.aspx.cs" Inherits="square" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <link rel="Stylesheet" type="text/css" href="geometry.css" /> <title> Geometry: Square </title> </head> <body> <form id=" frmSquare " runat="server" method="post" > <div> <table border="0" style="width: 660px"> <tr> <td style="width: 100%"> <p class="maintitle">Geometry: Square</p> </td> </tr> </table>   <table border="0" width="660"> <tr> <td> <p class="parajust">A square is a type of <a href="rectangle.aspx">rectangle</a> for which all 4 sides are equal. This means that the horizontal measurement, the base or length and the height are equal. The length of each side is then called the side of the square. A square can be represented as follows:</p> <p class="centered"><img src="images/square1.gif" alt="Square" /> </p> <p class="parajust">To process a square, you must have the measure of the side. This would allow you to calculate the perimeter and the area. To do this, you can use simple geometric formulas. Consider the following:</p> </td> </tr> </table>   <table> <tr> <td style="width: 660px"> <strong>S: side</strong> </td> </tr> <tr> <td style="width: 660px"> <strong>P: perimeter</strong> </td> </tr> <tr> <td style="width: 660px"> <strong>A: area</strong> </td> </tr> </table>   <table border="0" style="width: 660px"> <tr> <td style="width: 100%"> <p class="parajust">To calculate the values of a square, you can use the following formulas:</p></td> </tr> <tr> <td style="width: 100%"> <p class="formula">P = S * 4</p> </td> </tr> <tr> <td style="width: 100%"> <p class="formula">A = S * S</p> </td> </tr> </table> <hr /> <table> <tr> <td style="width: 100px"> <asp:Label ID="Label1" runat="server" Text="Side:"></asp:Label></td> <td style="width: 121px"> <asp:TextBox ID="txtSide" runat="server"></asp:TextBox></td> <td style="width: 100px"> <asp:Button ID="btnCalculate" runat="server" Text="Calculate" /></td> </tr> <tr> <td style="width: 100px"> <asp:Label ID="Label2" runat="server" Text="Perimeter"></asp:Label></td> <td style="width: 121px"> <asp:TextBox ID="txtPerimeter" runat="server"> </asp:TextBox></td> <td style="width: 100px"></td> </tr> <tr> <td style="width: 100px"> <asp:Label ID="Label3" runat="server" Text="Area:"></asp:Label></td> <td style="width: 121px"> <asp:TextBox ID="txtArea" runat="server"> </asp:TextBox></td> <td style="width: 100px"></td> </tr> </table> </div> </form> <table border="0" width="660"> <tr> <td colspan="2"> <hr /> </td> </tr> <tr> <td align="center"> <a href="index.aspx"> <strong><span style="font-size: 10pt">Home</span></strong> </a> </td> <td align="center"> <p class="centered">Copyright © 2009 NetConsulting, Inc.</p> </td> </tr> <tr> <td colspan="2"> <hr /> </td> </tr> </table> </body> </html>
  17. Save the files

Number Request#

In C#, everything the user types is a string and the compiler would hardly analyze it without your explicit asking it to do so. Therefore, if you want to get a number from the user, first get the string that represents the value. Here is an example:

C#
void Calculate()
{
        string strLength;

        strLength = txtLength.Text;
}

After getting the string, you must convert it to a number. To perform this conversion, each data type of the .NET Framework provides a mechanism called Parse. To use Parse, type the data type, followed by a period, followed by Parse, and followed by parentheses. In the parentheses of Parse, type the string that you requested from the user. Here is an example:

C#
void Calculate()
{
        string strLength;
        double Length;

        strLength = txtLength.Text;
        Length = double.Parse(strLength);
}

An advanced but faster way to do this is to type the string value in the parentheses of Parse. This has the same effect. Here is an example:

C#
void Calculate()
{
        double Length;

        Length = double.Parse(txtLength.Text);
}

Practical Learning: Reading Numeric Values

  1. If necessary, click the square.aspx tab to access its file. In the lower-left section of the window, click the Design button and, on the form, double-click the Calculate button
  2. To retrieve various numbers from the user, change the file as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class images_square : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnCalculate_Click(object sender, EventArgs e) { double side = double.Parse(txtSide.Text); double Perimeter = side * 4; double Area = side * side; } }
  3. Click the rectangle.aspx tab to access its file. In the lower-left section of the window, click the Design button and, on the form, double-click the Calculate button
  4. To retrieve various numbers from the user, change the file as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class images_rectangle : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnCalculate_Click(object sender, EventArgs e) { double Length; double Height; double Perimeter; double Area; Length = double.Parse(txtLength.Text); Height = double.Parse(txtHeight.Text); Perimeter = (Length + Height) * 2; Area = Length * Height; } }
  5. Sale the files

Requesting Dates and Times#

As done with the regular numbers, you can request a date value from the user. This is also done by requesting a string from the user. After the user has entered the string you can then convert it to a DateTime value. Just like any value you request from the user, a date or time value that the user types must be valid, otherwise, the program would produce an error. Because dates and times follow some rules for their formats, you should strive to let the user know how you expect the value to be entered. By default, if you request only a date from the user and the user enters a valid date, the compiler would add the midnight value to the date. If you request only the time from the user and the user enters a valid time, the compiler would add the current date to the value.

Formatting Data Display#

Conversion To String#

Once a value is ready, you can convert it to a string and display it on a web page. We mentioned earlier that everything the user types using the keyboard is primarily a string and it's your job to convert it to the appropriate type. In reverse, if you have a value that is not a string, you can convert it to a string. To support this, each .NET Framework data type provides a mechanism called ToString. To convert a value of a primitive data type to a string, type the name of the variable, followed by a period, followed by ToString(). Practical Learning: Converting to String

  1. To convert some values to string, change the event in the rectangle.aspx.cs file as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class images_rectangle : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnCalculate_Click(object sender, EventArgs e) { double Length; double Height; double Perimeter; double Area; Length = double.Parse(txtLength.Text); Height = double.Parse(txtHeight.Text); Perimeter = (Length + Height) * 2; Area = Length * Height; txtPerimeter.Text = Perimeter.ToString(); txtArea.Text = Area.ToString(); } }
  2. Click the square.aspx.cs tab to access its file and change the event as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class images_square : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnCalculate_Click(object sender, EventArgs e) { double side = double.Parse(txtSide.Text); double Perimeter = side * 4; double Area = side * side; txtPerimeter.Text = Perimeter.ToString(); txtArea.Text = Area.ToString(); } }
  3. Click the index.aspx tab and click the Source button
  4. In the head section of the code, add the following functions: <script type="text/javascript"> function ShowSquare() { javascript:window.open("square.aspx"); } function ShowRectangle() { javascript: window.open("rectangle.aspx"); } </script> </head>
  5. Click the Design button
  6. From the Standard section of the Toolbox, drag LinkButton and drop it in middle empty cell of the table of the from
  7. While the link button is selected, in the Properties window, change the following characteristics: (ID): lbSquare OnClientClick: ShowSquare() Text: Square
  8. To add another link button, on the form, click the right empty cell of the table
  9. On the Toolbox, double-click LinkButton
  10. While the link button is selected, in the Properties window, change the following characteristics: (ID): lbRectangle OnClientClick: ShowRectangle() Text: Rectangle <%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Geometry Tutorials</title> <style type="text/css"> .tablelinks { width: 300px; } </style> <script type="text/javascript"> function ShowCircle() { javascript:window.open("circle.aspx"); } function ShowSquare() { javascript: window.open("square.aspx"); } function ShowRectangle() { javascript: window.open("rectangle.aspx"); } </script> </head> <body> <h2>Geometry Tutorials</h2> <form id="frmGeometry" runat="server"> <div> <table class="tablelinks"> <tr> <td> <asp:LinkButton ID="lbCircle" runat="server" onclientclick="ShowCircle()">Circle </asp:LinkButton> </td> <td> <asp:LinkButton ID="lbSquare" runat="server" onclientclick="ShowSquare()">Square </asp:LinkButton> </td> <td> <asp:LinkButton ID="lbRectangle" runat="server" onclientclick="ShowRectangle()">Rectangle </asp:LinkButton> </td> </tr> </table> </div> </form> </body> </html>
  11. To execute the application, press Ctrl + F5
  12. From the index.aspx file, click the Rectangle link and provide some numeric values for the length and the height, then click the Calculate. Here is an example:
  13. Click the Home button
  14. From the index.aspx file, click the Square link and provide some numeric values for the length and the height, then click the Calculate. Here is an example:
  15. Return to your programming environment

Value Formatting#

To properly display data in a friendly and most familiar way, you can format it. Formatting specifies what kind of data you are using and how you want it to be displayed to the user. As it happens, you can display a natural number in a common value or, depending on the circumstance, you may prefer to show it as a hexadecimal value. When it comes to double-precision numbers, you may want to display a distance with three values on the right side of the decimal separator and in some cases, you may want to display a salary with only 2 decimal places. The System namespace provides a specific letter that you can use in the parentheses of ToString() for each category of data to display. To format a value, in the parentheses, between the double-quotes, type the appropriate letter from the following table:

CharacterUsed For
cCCurrency values
dDDecimal numbers
eEScientific numeric display such as 1.45e 5
fFFixed decimal numbers
gGGeneral and most common type of numbers
nNNatural numbers
rRRoundtrip formatting
xXHexadecimal formatting
pPPercentages

If you leave the parentheses of ToString() empty, the compiler would use a default formatting to display the value.

Data and Time Formatting#

As mentioned earlier, when the user enters a date value for a DateTime variable, the compiler adds a time part to the value. Fortunately, if you want to consider only the date or only the time part, you can specify this to the compiler. To support this, the DateTime data type provides a series of letters you can use to format how its value should be displayed to the user. The character is entered in the placeholder of the DateTime variable after the 0 or the incremental numeric value. Previous Copyright © 2008-2009 C# Key Next