Web 1

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 30

1

ASP.NET
ASP.NET has been greatly improved over the ASP technology in .Net. Some of the
important features of ASP.NET and the improvements over the classical ASP technology
include:
• ASP.NET is completely compiled code on the server side as opposed to
interpreted code in the traditional ASP technology. This helps improves the
performance of the web site greatly.
• ASP.NET is completely object-oriented as the entire code is written in one of the
.Net languages (C# being the most common and most powerful). Traditional ASP
used the ActiveX/COM technology to create tiered architectures and give the
server-side the code somewhat of an object-oriented feel. Traditional ASP also
used ActiveX/COM components to accomplish sophisticated tasks such as
sockets, sending emails, uploading files to the server etc.. ASP.NET eliminates the
need to use ActiveX/COM components as the entire framework class library is
available to accomplish any sophisticated task.
• ASP.NET provides a clean separation between the GUI and the server-side code.
Each web page typically has two parts to it: a .aspx file containing the HTML
presentation, and a code behind file (with .cs or .vb extension) containing the
related server-side code. Thus by default, the ASP.NET provides a 2-Tier
architecture which can be easily implemented as a multi-tier design as the
complexity of the web application increases.
• ASP.NET further improves the performance by providing powerful server-side
caching of the executed code for a faster response to the client.
• The associated ADO.NET technology for dealing with databases also has smart
caching of records available in the form of the dataset for a very high
performance data driven web application.
• ASP.NET is backwards compatible with the classical ASP technology.
• ASP.NET has a much easier deployment of web applications. Simply copy the
web application directory to a target machine and set up the appropriate virtual
directory to run the application.
• ASP.NET can use the ActiveX/COM components if needed through the RCW
(Runtime Class Wrapper) feature of .Net. Although all new development in
ASP.NET can be accomplished without the ActiveX/COM components.
• For creating scalable, tiered architectures, ASP.NET still uses the COM+
technology. However, the COM+ programming is made much simpler by the use
of special attributes that can be specified for the .Net classes that will be
converted to COM+ components.
• ASP.NET provides excellent client-side data validation in the form of specialized
validators. These validators generate the appropriate client-side Javascript code
for data validation on the client side. Thus the need to program in Javascript
directly on the client-side is greatly reduced.
• ASP.NET provides a powerful server-side event driven model for web application
development where different HTML elements (server controls) on the client-side
2

trigger events on the server-side (the associated code behind file for the aspx file
contains the event handlers for these events).
• ASP.NET provides a very easy way to maintain the state of client-side elements
once a server-side event is triggered by one of these elements and the form is
submitted to the server.
• ASP.NET provides an AutoPostBack property for server-side controls so that if
anything is changed in the control, the data is posted to the web server. For
example, if a checkbox is checked or unchecked, the server-side event handler can
be triggered if its AutoPostBack property is set to true.
• Although Visual Studio.Net is not required for developing ASP.NET applications,
it makes the web application development much easier by providing an array of
server-side controls, their visual placement and writing of the skeleton code for
the event handlers for these.
• ASP.NET and Visual Studio.NET provide powerful support for creating web
services and web services based distributed applications.

We will examine some of the above features of ASP.NET in detail and provide
appropriate examples to clarify the concepts.

Understanding Server-side Controls in ASP.NET:


As mentioned earlier, ASP.NET provides a powerful new concept in terms of
server-side controls and the associated event-driven programming model. In traditional
ASP, when we created a form, there needed to be a submit type button, and further the
action statement in the form indicated what will be target page that will process this
submitted form e.g., a traditional ASP page might look as,

<% @LANGUAGE=VBSCRIPT %>


<% 'Login.asp – traditional ASP example %>
<HTML>
<HEAD>
<TITLE> Login Form </TITLE>
</HEAD>
<BODY>
<H2> Web Site Logon </H2>
<H3> Please Specify User ID and Password</H3>
<HR>
<FORM name=frmLogin method=POST ACTION="VerifyLogin.asp">
<PRE>
User ID: <INPUT NAME="userID" SIZE="5" MAXLENGTH="5" VALUE="">
Password: <INPUT TYPE="password" NAME="password" VALUE="">
<INPUT TYPE=SUBMIT VALUE="Login" NAME=cmdLogin>
</PRE>
</FORM>
<HR>
</BODY>
</HTML>

The target of this page i.e., VerifyLogin.asp might look as:


3

<% @LANGUAGE=VBSCRIPT %>


<% 'VerifyLogin.asp – traditional ASP example %>
<HTML>
<HEAD>
<TITLE> Verifying Login </TITLE>
<script language=Javascript>
<!--
function Back( ) {
window.history.back(1);
}
-->
</script>
</HEAD>
<BODY>
<H2> Verifying User ID and Password </H2>
<HR>
<%
dim uid, pwd
uid = Request("userID")
pwd = Request("password")
' a real application will check the database to see if the submitted userID and password exist
' if so welcome the user else reirect the user to the login page
if (uid = "123") and (pwd="webclass") then
Response.write("Welcome :" & Request ("userID"))
else
Response.write("Incorrect User ID and Password, Click on the following button to try again")
Response.write("<input type=button name=btnBack value='Try Again' onclick='Back( );'>")
End if
%>
</BODY>
</HTML>

Now let us take a look at the same example in ASP.NET using the server
controls and the code behind page.

Create a new ASP.NET web application. Name the project Login as shown below i.e., set
the location to be http:://localhost/Login.
4

From the project explorer (top right hand corner), change the name of the
WebForm1.aspx file to Login.aspx.
We will use an HTML table to align the server controls in the Login form.
Click on the HTML tab and double click on the table element. This will end up drawing a
default 3x3 table.

By first selecting a cell in the table and then right clicking on it, you can choose to delete
rows or columns. Similarly by right clicking on a selected cell and clicking on the
properties, you can make a row span more than one column. Modify the table to have 3
rows and two columns such that the last row spans two columns, as shown below.
5

Type the text “User ID” and Password in the two left cells of the first column of the table.
Then select the Web Form controls from the toolbox. First click on the top right hand cell
of the table, then double click on the text box control. Similarly drop another text box
control in the cell below it, and a button in the last cell. Select the first text box, give an
ID of “txtUserID” to the first text box, and similarly after selecting the second text box,
give it an ID of “txtPassword”. Set the TextMode property of the text box to “Password”.
Select the button, and from its properties, give it an ID of cmdLogin and Text property of
“Login”. Set the alignment of the last cell in the table to be horizontal center.
Select the entire table and move it a few lines below from the top left hand corner of the
page. By right clicking on the table and selecting properties, you can set the border size
of the table to be zero pixels so that the table does not appear in the browser.
Double click on the Login button to write a server-side event handler for it. Type the
following code in the click event handler of the button. Note that the code is typed in the
“code behind” file which has a name of “Login.aspx.cs”.

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;
6

namespace Login
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox txtUserID;
protected System.Web.UI.WebControls.TextBox txtPassword;
protected System.Web.UI.WebControls.Button cmdLogin;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form 
Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support ­ do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{    
this.cmdLogin.Click += new 
System.EventHandler(this.cmdLogin_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void cmdLogin_Click(object sender, 
System.EventArgs e)
{
string uid, pwd;
uid = txtUserID.Text;
pwd = txtPassword.Text;
//a real application will check the database to see 
//if the submitted userID and password exist
7

//if so welcome the user else reirect the user 
//to the login page

if ((uid == "123") && (pwd == "webclass"))
Response.Write("Welcome :" + uid);
else
{
Response.Write("Incorrect Login, Click on the button 
to try again");
Response.Write("<input type=button name=btnBack 
value='Try Again' onclick='Back();'>");
}
}
}
}

You need to add a client-side javascript function to the Login.aspx file. Using the HTML
tab on this file, you can add the javascript code as shown below. Some of the important
sections of code are shown in bold.

<%@ Page language="c#" Codebehind="Login.aspx.cs"


AutoEventWireup="false" Inherits="Login.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
<script language="javascript">
function Back() {
window.history.back(1);
}
</script>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<TABLE id="Table1" style="Z-INDEX: 101; LEFT: 10px; POSITION: absolute; TOP: 68px"
cellSpacing="1" cellPadding="1" width="300" align="center" border="1">
<TR>
<TD>User ID</TD>
<TD>
<asp:TextBox id="txtUserID" runat="server"></asp:TextBox></TD>
</TR>
<TR>
<TD>Password</TD>
8

<TD>
<asp:TextBox id="txtPassword" runat="server"
TextMode="Password"></asp:TextBox></TD>
</TR>
<TR>
<TD align="middle" colSpan="2">
<asp:Button id="cmdLogin" runat="server"
Text="Login"></asp:Button></TD>
</TR>
</TABLE>
</form>
</body>
</HTML>

Taking a look at the Login.aspx file, some of the important things to note
are:
1. The aspx file is associated with the code behind file as specified in the first line
of the aspx file, e.g., in our Login example, the first line of Login.aspx is:
<%@ Page language="c#" Codebehind="Login.aspx.cs"
AutoEventWireup="false" Inherits="Login.WebForm1" %>
The CodeBehind and the Inherits attributes above tie the aspx file to the code file
and the class contained in it from which the entire aspx file will be derived.

2. The server controls need to be contained in a form which ahs the runat=server
specified.
<form id="Form1" method="post" runat="server">

3. Each Web form server control is specied with the tag <asp:controlname
id=”name” runat=”server”/> e.g.,
<asp:TextBox id="txtPassword" runat="server"
TextMode="Password"></asp:TextBox>

If you build the solution, and then go to the browser and type
http://localhost/Login/Login.aspx, you will see the following output if you enter a user ID
of 123 and a password of “webclass”.

If some other password is entered, then the output will look as:
9

Panel Control:
Just like in a Windows application, there is a panel control which is used to group
other controls, similarly there is a panel server control available in web forms. We can
use it to improve the reporting of results in our Login application. For example, if you do
not move the table a few lines from the top of the form, you will notice that all the Login
results (i.e., whether a login is successful or not) are written right on top of the Login
form as shown below.

Obviously, the above output does not look nice. We can correct this problem by putting
the Login form controls inside a panel and making the panel invisible in the click event
handler of the login button.
Select the table in the Login.aspx file and choose edit->cut. Then from the web form
controls, double click on the Panel control. You can size it to contain the Login form.
Change the ID of the panel on the page to pnlLogin. Then you can paste the Login form
on top of the panel. Modify the click event of the Panel control to include the following
line in the beginning of the event handler code.
pnlLogin.Visible = false;

Rebuild and test the solution again. Now the output after Loggin in will appear as:
10

Thus panel control provides somewhat equivalent of the layers capability on the client
side but has a much easier server side control to the visibility of an area.
Panel control can be used not only to group controls and control their visibility and
appearance, it can also be used to generate controls programmatically. A panel can be also
be given some kind of background image by its “BackImageURL” property. You can also
align the controls in it with the “HorizontalAlign” property.

Example: Creating controls dynamically inside a Panel.


Add another panel to the Login.aspx file below the Login form. Give this panel an ID of
pnlDynamic. Add a drop down list box from the web form controls below the second
panel. Give an ID of ddlNumBoxes. Set the AutoPostBack property of the drop down list
box to true. If AutoPostBack property for a control is set to true, then an event for that
control will cause the form data to be posted to the web server. In the Items collection
property of the list box, add three numbers (1,2,3) with values of 1, 2 and 3 respectively.
Add a label next to the drop down list box with a Text property of “Choose Number of
Text Boxes”, as shown below.
11

Add an event handler for the SelectedIndexChanged event of the drop down list box.
Write the following code in the SelectedIndexChanged event of the list box in the
Login.aspx.cs file.
private void ddlNumBoxes_SelectedIndexChanged(object sender, 
System.EventArgs e)
{
int numBoxes = int.Parse(ddlNumBoxes.SelectedItem.Value);
for (int i = 1; i <= numBoxes; i++)
{
Label lbl = new Label();
lbl.ID = "lblL" + i.ToString();
pnlDynamic.Controls.Add(lbl);

TextBox txt = new TextBox();
txt.ID = "txtT" + i.ToString();
pnlDynamic.Controls.Add(txt);
pnlDynamic.Controls.Add(new LiteralControl("<br>"));
}
for (int i = 0; i < pnlDynamic.Controls.Count; i++)
{
if( pnlDynamic.Controls[i] is Label)
{
Label l1 = (Label) pnlDynamic.Controls[i];
if (l1.ID == "lblL1")
l1.Text = "First Name";
if (l1.ID == "lblL2")
l1.Text = "Last Name";
if (l1.ID == "lblL3")
l1.Text = "Student ID";
}
}

Examine the above code carefully to understand how controls can be created dynamically
and added to the panel, and also how can we later set or read the property of a dynamic
control inside the panel.

Part of the HTML that is generated in the Login.aspx file when we added the second
panel, the drop down list box and the label is shown below:

<asp:DropDownList id="ddlNumBoxes" style="Z-INDEX: 103; LEFT: 204px;


POSITION: absolute; TOP: 303px" runat="server" AutoPostBack="True">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:DropDownList>&nbsp;
<asp:Panel id="pnlDynamic" style="Z-INDEX: 102; LEFT: 12px; POSITION:
absolute; TOP: 148px" runat="server" Width="322px"
Height="140px">Panel</asp:Panel>
12

<asp:Label id="Label1" style="Z-INDEX: 104; LEFT: 96px; POSITION:


absolute; TOP: 296px" runat="server" Width="104px" Height="51px">Choose Number
of Text Boxes</asp:Label>

You can delete the word “Panel” from the asp:Panel control specification above. This is
simply a static text that is displayed on the screen on the panel.

If you build and test the application, a drop down list box will appear. Once you choose
the number of Text boxes to dynamically generate in the second panel, the result will
appear as.

Experiment by setting the AutoPostBack property of the drop down list box to false. After
you rebuild the application and test it, you will notice that as you change the number in
the drop down list box, the number of text boxes does not change in the second panel.
However, if you click on the Login button, then the form data is posted to the web server
and the number of text boxes will be correctly generated in the second panel.

As you can see from the examples presented in this section that the ASP.NET
programming model is very similar to the Windows forms event driven programming
model. This is one reason the ASP.NET pages are referred to as Web Forms. The server
controls on the web form generate events, and if the AutoPostBack property of the
control causing the event is set to true, an immediate posting of form data occurs to the
server and the appropriate event handler for the event is executed. One major difference
in web forms from the windows event driven model is that some events cannot be posted
to the server. For example the “MouseMove” event cannot be provided a server-side
event handler in ASP.NET as it will cause tremendous posting of data and would
deteriorate the web application performance.
13

From learning point of view, one of the first things to master in ASP.NET is the different
ASP server controls available and the use of their properties and events. Note that
ASP.NET is backwards compatible with classic ASP and provides the built-in objects of
Request, Response, Session and Application. We will first cover the ASP.NET server
controls, and then take a look at the session and application management in ASP.NET.
14

HTML and ASP Server Controls


ASP.NET provides two kinds of server controls. One are called HTML server
controls and the other as ASP server controls. The HTML server controls are similar to
the HTML elements with the addition of runat=server attribute in the declaration of the
control. An associated server-side event can be written in the same file between the
<script runat=server> </script> tags.
The HTML server controls have the benefit that a client-side event handler can be
specified for them.

HTML server control Example:


Using notepad, create a file called HTMLServerCtl.aspx with the following code in it:
You can create a new directory called ASPNET where the above file will be stored. Then
using the Internet Services Manager, you can set up a virtual directory called an to point
to the ASPNET directory.

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


<% // HTMLServerCtl.aspx %>
<html>
<script language="javascript">
function Validate() {
var val;
val = parseInt(document.frmST.txtID.value);
if (isNaN(val))
{
alert("ID must be integers");
window.event.returnValue=false;
}
}
</script>

<script runat=server>
void btnSubmit_Click(Object source, EventArgs e)
{
lblOutput.Value = txtName.Value + ":" + txtID.Value;
}
</script>

<body>
<h1> Test of HTML Server Controls </h1>
<pre>
<form id="frmST" runat="server">
Name : <input type="text" ID="txtName" runat="server" />
ID : <input type="text" id="txtID" runat="server" />
<input type="submit" id="btnSubmit" value="Enter Data"
runat="server" onclick="Validate();" onServerClick="btnSubmit_Click" />
<br/>
15

Data Entered: <input type="text" value="" id="lblOutput" size="30" runat="server" />


<br/>
</form>
</pre>
</body>
</html>

ASP Server Controls:


ASP Server Controls are the preferred way to use controls in web pages. These have
the syntax as:
<asp:controlname id=”name” runat=”server”/>
e.g.,
<asp:TextBox id="txtPassword" runat="server"
TextMode="Password"></asp:TextBox>

There are two benefits to using the ASP server controls over the HTML server controls.
The first one is that the ASP server controls have a more uniform object model in terms
of accessing the properties and events of the controls. For example, most controls provide
the Text property for reading the value of the control (note that the HTML server controls
mostly use the value property). The second benefit to using ASP server controls is that
there are server-side validators available that generate the appropriate client-side code for
data validation on the client-side.

The validators in ASP server controls examine the HttpRequest object and determine
the browser type in the request. Based on the browser type and version detected, the
validators generate appropriate client-side code automatically. This way, you as a
programmer can focus on implementing the proper logic in the web application without
having to worry about generating the browser-specific client-side code for data validation
on the client side.
16

Example: It is possible to write all the code involving ASP server controls and their
event handlers in one file. Let us modify the previous example to work with ASP server
controls instead of HTML server controls. Using Notepad, type the following code in a
file called ASPServerCtlTest.aspx. The important differences from the HTML server
controls are shown in bold.

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


<% // ASPServerCtlTest.aspx %>
<html>
<!-- client-side validation to be done by ASP server Validators -->
<script runat=server>
void btnSubmit_Click(Object source, EventArgs e)
{
lblOutput.Text = txtName.Text + ":" + txtID.Text;
}
</script>

<body>
<h1> Test of ASP Server Controls </h1>
<pre>
<form id="frmST" runat="server">
Name : <asp:textBox ID="txtName" runat="server" />
ID : <asp:textBox id="txtID" runat="server" />
<asp:button id="btnSubmit" Text="Enter Data"
runat="server" onClick="btnSubmit_Click" />
<br/>
Data Entered: <asp:label value="" id="lblOutput" size="30"
runat="server" />
<br/>
</form>
</pre>
</body>
</html>

As you can see from the above example, the ASP server controls use the Text property
instead of value to read the data from a text box or to put a caption on a button. Further,
the onClick handler for a button refers to the server-side event handler and not the client
side code. For client-side validation, we will need to use the ASP server validators which
will be described later.

Although, we can type the code displaying the controls and the associated event handlers
in the same file, it is a better practice to separate the two where the presentation will go in
the .aspx file and the code for the event handlers and the server-side processing in the
associated .aspx.cs file (if you are using C# for ASP development). When you use Visual
Studio.Net, it automatically creates the two files for each web page in the application.
17

ASP Server Button, Label and Text Box Controls:


ASP server controls include three kinds of buttons and one very flexible text box
control. The label control provides a read only area to the client with the capability to
specify different font sizes and backgrounds in it.

The three button controls are:


1. Button – acts like a submit button
2. LinkButton – acts like a hyperlink whose click event handler can redirect to a
page.
3. ImageButton – acts like an image button whose click event handler can redirect to
a page.

The link button uses the client-side code generated automatically from the server-side
code to redirect to the url specified in its click event handler. There is also a simple
Hyperlink ASP server control that generates a simple hyperlink client-side code. The
benefit of the Hyperlink control is that you can use the Target attribute to open the target
page either in a new browser window (Target = _blank) or to direct it to a particular
window.

When dealing with multiple buttons in a user interface, often we may want to provide a
single event handler for the different buttons. In this case, the ASP server button provides
a CommandName property which can be set differently for each button. The
CommandName is passed as the second parameter to the click event handler of a button.

The ASP textbox control has a TextMode property that allows you to have either a single-
line or a multi-line text box, or a text-box of the password type. If the TextMode property
is specified to be multi-line, then the Rows property is further used to indicate how many
rows will this text box have.

Example:
Create a new ASP.NET web forms application. Name the URL
http://localhost/ASPServerCtls.
Change the name of default page Webform1.aspx to Main.aspx. Put a label and a link
button on the main page that looks as shown below.
18

You can set the font size, the back color and the fore color properties of the label. Set the
text property of the label to “Test of Different Server Controls”.
As you can see, the text property of the link button is set to “Buttons, Text Box, Test”.
Give an ID of lnkTxtBtTest to the link button. Double click on the link button to write the
event handler for it. The code for the link button click event handler is:

private void lnkTxtBtTest_Click(object sender, System.EventArgs e)
{
Response.Redirect("TxtBtTest.aspx");
}

By right clicking on the project name in the project explorer, add a new web form to the
project. Name the web form “TxtBtTest.aspx”. Add an HTML table to this form with 5
rows and two columns. The table will have labels and text boxes as shown above. The
five text boxes have Ids of txtFname, txtLname, txtID, txtEmail and txtComments. The
last text box has TextMode property set to “MultiLine” and the Rows property set to 3.
Add a button to the bottom of the table with an ID of “btnCheckData” and a Text
property of “Check Entered Data”. Next to this button, add a link button with an ID of
“lnkMain” and the text property of “Back to Main Page”. Add an image button with an
ID of “imgBtnBack” and ImageURL property pointing to a jpeg file that you have copied
to the Images subfolder in your web application directory (e.g., in my case it is
c:\inetpub\wwwroot\ASPServerCtls\Images). The code for the different event handlers in
the TxtBtTest.aspx.cs file is shown below:

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


{
19

string Data="";
Data = Data + "First Name: " + txtFname.Text;
Data = Data + "<BR>Last Name: " + txtLname.Text;
Data = Data + "<BR>ID: " + txtID.Text;
Data = Data + "<BR>Email: " + txtEmail.Text;
Data = Data + "<BR>Comments: " + txtComments.Text;

lblDataEntered.Text = Data;
}

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


{
Response.Redirect("Main.aspx");
}

private void imgBtnBack_Click(object sender,


System.Web.UI.ImageClickEventArgs e)
{
Response.Redirect("Main.aspx");
}

Build and test the application.

Example: A simple calculator showing how to assign a single event handler to multiple
buttons, and the use of session objects.
Add a web form to the ASPServerCtls application. Name the web form Calc.aspx. Put
an HTML table on the form with 5 rows and four columns. Make the first row span four
columns. Add an ASP server label to the first row in the table with an ID of lblDisplay.
You can set the back color and the font to your liking. Then drop ASP server buttons in
the table as shown below.

The button with caption “0” has an ID of btnZero, a CommandName of “Zero”. Similarly
button “9” has an ID of btnNine, and a CommandName property of “Nine. Note that the
20

CommandName property is being used so that these numeric buttons (and the decimal
button) can have a common event handler. The second parameter of the Command event
handler for these buttons can be examined to find the CommandName to determine
which button is clicked.
Add a Command event handler for the “0” button. Change the name of the event
handler to btn_Command. Note that you will have to also change the delegate for the
Command event handler in the Web Form Designer Generated Code. You can manually
add the delegates for the numeric buttons and the decimal button in the Web Form
Designer generated code. It should look as:
this.btnZero.Command += new 
System.Web.UI.WebControls.CommandEventHandler(this.btn_Command);
this.btnOne.Command += new 
System.Web.UI.WebControls.CommandEventHandler(this.btn_Command);
this.btnTwo.Command += new 
System.Web.UI.WebControls.CommandEventHandler(this.btn_Command);
this.btnThree.Command += new 
System.Web.UI.WebControls.CommandEventHandler(this.btn_Command);
this.btnFour.Command += new 
System.Web.UI.WebControls.CommandEventHandler(this.btn_Command);
this.btnFive.Command += new 
System.Web.UI.WebControls.CommandEventHandler(this.btn_Command);
this.btnSix.Command += new 
System.Web.UI.WebControls.CommandEventHandler(this.btn_Command);
this.btnSeven.Command += new 
System.Web.UI.WebControls.CommandEventHandler(this.btn_Command);
this.btnEight.Command += new 
System.Web.UI.WebControls.CommandEventHandler(this.btn_Command);
this.btnNine.Command += new 
System.Web.UI.WebControls.CommandEventHandler(this.btn_Command);
this.btnDecimal.Command += new 
System.Web.UI.WebControls.CommandEventHandler(this.btn_Command);

The different event handlers in the Calc.aspx.cs look as:

private void btn_Command(object sender, 
System.Web.UI.WebControls.CommandEventArgs e)
{
switch(e.CommandName)
{
case "Zero" :
lblDisplay.Text = lblDisplay.Text + "0";
break;
case "One" :
lblDisplay.Text = lblDisplay.Text + "1";
break;
case "Two" :
lblDisplay.Text = lblDisplay.Text + "2";
break;
case "Three" :
lblDisplay.Text = lblDisplay.Text + "3";
break;
21

case "Four" :
lblDisplay.Text = lblDisplay.Text + "4";
break;
case "Five" :
lblDisplay.Text = lblDisplay.Text + "5";
break;
case "Six" :
lblDisplay.Text = lblDisplay.Text + "6";
break;
case "Seven" :
lblDisplay.Text = lblDisplay.Text + "7";
break;
case "Eight" :
lblDisplay.Text = lblDisplay.Text + "8";
break;
case "Nine" :
lblDisplay.Text = lblDisplay.Text + "9";
break;
case "Decimal" :
lblDisplay.Text = lblDisplay.Text + ".";
break;
}
}

private void btnClear_Click(object sender, System.EventArgs e)
{
lblDisplay.Text="";
}

private void btnPlus_Click(object sender, System.EventArgs e)
{
double num1=double.Parse(lblDisplay.Text);
lblDisplay.Text="";
Session["num1"] = num1;
Session["operation"]="+";
}

private void btnEqual_Click(object sender, System.EventArgs e)
{
double num2=double.Parse(lblDisplay.Text);
double num1 = (double)Session["num1"];
string op = (string) Session["operation"];
double result=0.0;
switch (op)
{
case "+" : result = num1 + num2; break;
case "­" : result = num1 ­ num2; break;
case "*" : result = num1 * num2; break;
case "/" : result = num1 / num2; break;
}
lblDisplay.Text = result.ToString();
}
22

private void btnMinus_Click(object sender, System.EventArgs e)
{
double num1=double.Parse(lblDisplay.Text);
lblDisplay.Text="";
Session["num1"] = num1;
Session["operation"]="­";
}

private void btnMultiply_Click(object sender, System.EventArgs e)
{
double num1=double.Parse(lblDisplay.Text);
lblDisplay.Text="";
Session["num1"] = num1;
Session["operation"]="*";
}

private void btnDivide_Click(object sender, System.EventArgs e)
{
double num1=double.Parse(lblDisplay.Text);
lblDisplay.Text="";
Session["num1"] = num1;
Session["operation"]="/";
}

The code in the Page_Load event handler needs to be modified so that the label is cleared
first time the calculator page is seen by the client.
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack) // without this only one dig will appear 
lblDisplay.Text = "";
}

Note that the interesting thing in the above code is the use of Session objects to store the
first number being operated upon and the operation (+, -, * or /) being selected. Even
though the web form programming is very similar to windows forms, you cannot use data
members in the code behind class to store any information as each time a button is
pressed on the calculator, the data is posted to the web application and the data members
will be initialized to their default values and thus you will loose the pervious information.

You can add an ASP Hyperlink control to the Main.aspx file to point to the Calc.aspx file.
Set the Target property of the hyperink to _blank so that the calculator opens in a new
browser window. Also set the NavigateURL property to Calc.aspx, and the Text property
to “Simple Calculator”.
23

ASP Check Boxes and Radio server controls:


A check box allows you to make multiple selections whereas you can make only
one selection from a group of radio controls. The radio control provides a GroupName
property to make a group of related radio controls. ASP check boxes and radio controls
are very similar to each other in the sense that both generate the CheckedChanged server-
side event. The CheckedChanged event can be immediately handled provided the
AutoPostBack property Also, in order to determine if the check box or a radio button is
checked or unchecked, there is a Checked property for the controls that is tested.
Example: Add a web form to the previous application. Name the form CheckRadio.aspx.
Put some labels, check boxes, radio buttons and HTML Horizonal rules as shown below.
24

The bottom most lablel has an ID of lblSelections and will be used to display the
selections made dynamically. The top three check boxes have Ids of chkSalad, chkSoup,
and chkOnionRings. All check boxes and radio buttons have the AutoPostBack property
set to true so that each time you check or uncheck a control, the form is posted to the web
server. Even though in a real application, you may not set the AutoPostBack property to
true for all controls in the form, and instead have a single button that posts the form, we
are setting the AutoPostBack property to true for all controls to learn the event handling
on the server side.
The three radio buttons in the middle have IDs of optPizza, optSteak and optFish
respectively. These radio buttons have the GroupName property set to “DinnerItem”. The
last row of radio buttons have IDs of optChocolateCake, optCheeseCake and
optIceCream respectively. These radio buttons have GroupName property of
“DessertItem”.
The first set of radio buttons have a common event handler that you can specify in the
web forms designer code section. Similarly the last set of radio buttons also have a
common event handler.

this.optPizza.CheckedChanged += new 
System.EventHandler(this.dinner_CheckedChanged);
25

this.optSteak.CheckedChanged += new 
System.EventHandler(this.dinner_CheckedChanged);
this.optFish.CheckedChanged += new 
System.EventHandler(this.dinner_CheckedChanged);
this.optChocolateCake.CheckedChanged += new 
System.EventHandler(this.dessert_CheckedChanged);
this.optCheeseCake.CheckedChanged += new 
System.EventHandler(this.dessert_CheckedChanged);
this.optIceCream.CheckedChanged += new 
System.EventHandler(this.dessert_CheckedChanged);

The different event handlers for the check boxes and radio buttons are shown below.

private void chkSalad_CheckedChanged(object sender, System.EventArgs e)
{
CheckControls();
}

private void CheckControls()
{
string appetizer="Appetizer: ";
if (chkSalad.Checked == true)
appetizer = appetizer + "Salad " ;
if (chkSoup.Checked == true)
appetizer = appetizer + " Soup " ;
if (chkOnionRings.Checked == true)
appetizer = appetizer + " Onion Rings " ;

string dinner="Dinner Item: ";
if (optPizza.Checked == true)
dinner = dinner + "Pizza " ;
if (optSteak.Checked == true)
dinner = dinner + "Steak " ;
if (optFish.Checked == true)
dinner = dinner + "Fish " ;

string dessert="Dessert Item: ";
if (optChocolateCake.Checked == true)
dessert = dessert + "Chocolate Cake" ;
if (optCheeseCake.Checked == true)
dessert = dessert + "Cheese Cake" ;
if (optIceCream.Checked == true)
dessert = dessert + "Icecream Sundae" ;

lblSelections.Text = "Your selections: " +
   appetizer + dinner + dessert;
}
26

private void chkSoup_CheckedChanged(object sender, System.EventArgs e)
{
CheckControls();
}

private void chkOnionRings_CheckedChanged(object sender, 
System.EventArgs e)
{
CheckControls();
}

private void dinner_CheckedChanged(object sender, System.EventArgs e)
{
CheckControls();
}

private void dessert_CheckedChanged(object sender, System.EventArgs e)
{
CheckControls();
}

Add an ASP Hyperlink to the Main.aspx to point to the CheckRadio.aspx file. Build and
test the application.

ASP CheckBoxList, RadioButtonList, ListBox and DropDownList controls:


The CheckBoxList and RadioButtonList controls allow dynamic creation of check
boxes and radio buttons, and also allow dynamic creation from a data source. All of these
four controls have a SelectedIndex and SelectedItem property that you can examine to
27

find the index or the item selected. The Selected property is true for the item that is
selected. All of the four controls generate the SelectedIndexChanged event.

ASP MultiLine Text Box Control:


ASP Text box control has a multilane property wheich when set to true causes the
control to be rendered as <TextArea> …</TextArea> in HTML.

ASP.NET Calendar Control:


The ASP.NET calendar control is very useful in having the client choose dates. It is
rendered as a table with client side Javascript code that can post this form once the date is
chosen.
The calendar control can display a particular month. The user can pick a day, a
range of days, week, or month. It also allows the user to move to next or previous month.
The popular events for the calendar control are SelectionChanged,

You can choose a particular month to be displayed by setting the TodaysDate property of
the calendar control, e.g., if you have dropped a calendar control with an ID of “cal” on a
web form, then to display the January 1, 1990 calendar month, you will write the
following code in the page load event.
if (!IsPostBack)
{
DateTime dt = new DateTime(1990,1,1);
cal.TodaysDate = dt;
}

Example: Add a web form called CalendarTest.aspx to the ASPServerCtls project. Add
a label with the text property of “Choose a date from the Calendar”. Add a calendar
control. Give it an ID of “cal”. Write the following code in the Page_Load event of the
CalendarTest.aspx.cs file.
if (!IsPostBack)
{
cal.TodaysDate = DateTime.Now;
cal.SelectedDate = DateTime.Now;
}

Add a label with an ID of lblSelectedDate towards the bottom of the form. You can also
add a hyperlink to the “CalendarTest.aspx” file in the Main.aspx file of the
ASPServerCtls web application.

Double click on the calendar control to write the SelectionChanged event handler. Write
the following code in it.
private void cal_SelectionChanged(object sender, 
System.EventArgs e)
{
28

DateTime dt = cal.SelectedDate;
lblSelectedDate.Text = dt.ToShortDateString();
}

You can experiment with the different style properties of the calendar control through the
VS.Net properties window.

Creating Server Controls Dynamically:


Server controls can be created at runtime. The asp.net page maintains a Controls
collection to which the server control must be added after you have created it using the
new operator. For example, the page load event may contain the following code to create
a label dynamically.

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
Label lblDyn = new Label();
lblDyn.ID = "lblDynamic";
lblDyn.Text = "Dynamically Created Label";
this.Controls.Add(lblDyn);
}
The above code will position the label in the top left hand corner of the page. To position
a dynamically created control at a particular position, you can first create a panel using
29

the VS.Net (recall that a panel is a control container), then you can add your control to
the panel. If you need event handlers for the dyamic control, you can add a delegate to it
as demonstrated by the following example.

Example:
Add a web form called DynamicControls to the ASPServerCtls project. Write the
following code in the Page_Load event of the page.
private void Page_Load(object sender, System.EventArgs 
e)
{
// Put user code to initialize the page here

Label lblDyn = new Label();
lblDyn.ID = "lblDynamic";
lblDyn.Text = "Dynamically Created Label";
//this.Controls.Add(lblDyn);
pnlLogin.Controls.Add(lblDyn);
Button btn = new Button();
btn.ID = "btnLogin";
btn.Text = "Login Please";
pnlLogin.Controls.Add(btn);
btn.Command += new 
System.Web.UI.WebControls.CommandEventHandler(this.btnLogin_
Click);
}

// manually added function
private void btnLogin_Click(object sender, 
System.Web.UI.WebControls.CommandEventArgs e)
{  // dynamic button handler
Response.Write(pnlLogin.Controls.Count);
foreach (Control ct in pnlLogin.Controls)
{
if ((ct is Label) && (ct.ID=="lblDynamic"))
{
Label lb = (Label) ct;
lb.Text = "Hi";
}
}
}

The results will look as shown below.


30

After you click on the button, the label will change to “Hi” as shown below.

You might also like