Anda di halaman 1dari 75

Accepting File Uploads

Important properties, events

Enabled: disable the FileUpload control.

FileBytes: get the uploaded file as a byte array.

FileContent: get the uploaded file as a stream.

FileName: get the name of the file uploaded.

HasFile: Returns True when a file has been uploaded.

PostedFile: get the uploaded file wrapped in the HttpPostedFile object.

Focus: set the form focus to the FileUpload control.

SaveAs: save the uploaded file to the file system.

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


<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

protected void btnAdd_Click(object sender, EventArgs e)


{
if (upImage.HasFile)
{
if (CheckFileType(upImage.FileName))
{
String filePath = "~/UploadImages/" + upImage.FileName;
upImage.SaveAs(MapPath(filePath));
}
}
}

bool CheckFileType(string fileName)


{
string ext = Path.GetExtension(fileName);
switch (ext.ToLower())
{
case ".png":
return true;
case ".jpg":
return true;
default:
return false;
}
}

void Page_PreRender()
{
string upFolder = MapPath("~/UploadImages/");
DirectoryInfo dir = new DirectoryInfo(upFolder);
dlstImages.DataSource = dir.GetFiles();
dlstImages.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>FileUpload File</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Label
id="lblImageFile"
Text="Image File:"
AssociatedControlID="upImage"
Runat="server" />

<asp:FileUpload
id="upImage"
Runat="server" />

<br /><br />

<asp:Button
id="btnAdd"
Text="Add Image"
OnClick="btnAdd_Click"
Runat="server" />

<hr />

<asp:DataList
id="dlstImages"
RepeatColumns="3"
runat="server">
<ItemTemplate>
<asp:Image ID="Image1"
ImageUrl='<%# Eval("Name", "~/UploadImages/{0}") %>'
style="width:200px"
Runat="server" />
<br />
<%# Eval("Name") %>
</ItemTemplate>
</asp:DataList>

</div>
</form>
</body>
</html>

3. 19. 2. FileUpload Test

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="FileUploadTest" %>

<!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>FileUpload Control Test</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Choose a file to upload to the server<br />
<asp:FileUpload ID="fupTest" runat="server" Width="400px"/>
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload File"
OnClick="btnUpload_Click" />
<asp:Label ID="labMessage" runat="server"></asp:Label>
<asp:Label ID="labInfo" runat="server"></asp:Label>
</div>
</form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class FileUploadTest : System.Web.UI.Page


{
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
if (fupTest.HasFile)
{
string path = @"C:\temp\";
string fullname = path + fupTest.FileName;
if (System.IO.File.Exists(fullname))
{
labMessage.Text = "File already exists - uploaded cancelled";
}
else
{
fupTest.SaveAs(fullname);
labMessage.Text = "File successfully uploaded";

int contentLength = fupTest.PostedFile.ContentLength;


string contentType = fupTest.PostedFile.ContentType;
labInfo.Text = "Content Type = " + contentType;
labInfo.Text += "<br/>";
labInfo.Text += " Content Length = " + contentLength;
byte[] input = new byte[contentLength];
input = fupTest.FileBytes;

System.IO.Stream myStream = fupTest.FileContent;


int index = 0;
while (index < myStream.Length)
{
byte aByte = (byte)myStream.ReadByte();
index++;
}

}
}
else
{
labMessage.Text = "File was not specified";
}
}
catch
{
labMessage.Text = "File was not uploaded";
}
}
}

Upload file to server

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="UploadFile" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="Uploader" runat="server" Height="24px" Width="472px"
/>&nbsp;
<asp:Button ID="cmdUpload" runat="server" Height="24px"
OnClick="cmdUpload_Click"
Text="Upload" Width="88px" /><br />
<br />
<asp:Label ID="lblInfo" runat="server" EnableViewState="False" Font-
Bold="True"></asp:Label></div>
</form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class UploadFile : System.Web.UI.Page


{
private string uploadDirectory;
protected void Page_Load(object sender, EventArgs e)
{
uploadDirectory = Path.Combine(Request.PhysicalApplicationPath, "Uploads");
}

protected void cmdUpload_Click(object sender, EventArgs e)


{
if (Uploader.PostedFile.FileName == "")
{
lblInfo.Text = "No file specified.";
}
else
{
string extension = Path.GetExtension(Uploader.PostedFile.FileName);
switch (extension.ToLower())
{
case ".png":
case ".jpg":
break;
default:
lblInfo.Text = "This file type is not allowed.";
return;
}
string serverFileName = Path.GetFileName(Uploader.PostedFile.FileName);
string fullUploadPath = Path.Combine(uploadDirectory,serverFileName);

try
{
Uploader.PostedFile.SaveAs(fullUploadPath);

lblInfo.Text = "File " + serverFileName;


lblInfo.Text += " uploaded successfully to ";
lblInfo.Text += fullUploadPath;
}
catch (Exception err)
{
lblInfo.Text = err.Message;
}
}
}
}

Uploading files using the new FileUpload control (C#)

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

<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
try {
FileUpload1.SaveAs("C:\\Uploads\\" + FileUpload1.FileName);
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "<br>" +
FileUpload1.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex) {
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "You have not specified a file.";
}
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >


<head id="Head1" runat="server">
<title>FileUpload Server Control</title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" Runat="server" />

<asp:Button ID="Button1" Runat="server" Text="Upload"


OnClick="Button1_Click" />

<asp:Label ID="Label1" Runat="server"></asp:Label>


</form>
</body>
</html>

Uploading files using the new FileUpload control (VB)

<%@ Page Language="VB"%>

<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If FileUpload1.HasFile Then
Try
FileUpload1.SaveAs("C:\Uploads\" & _
FileUpload1.FileName)
Label1.Text = "File name: " & _
FileUpload1.PostedFile.FileName & "<br>" & _
"File Size: " & _
FileUpload1.PostedFile.ContentLength & " kb<br>" & _
"Content type: " & _
FileUpload1.PostedFile.ContentType
Catch ex As Exception
Label1.Text = "ERROR: " & ex.Message.ToString()
End Try
Else
Label1.Text = "You have not specified a file."
End If
End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >


<head id="Head1" runat="server">
<title>FileUpload Server Control</title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" Runat="server" />

<asp:Button ID="Button1" Runat="server" Text="Upload"


OnClick="Button1_Click" />

<asp:Label ID="Label1" Runat="server"></asp:Label>


</form>
</body>
</html>

Changing the file-size limitation setting in the web.config file

<httpRuntime
idleTime="15"
executionTimeout="90"
maxRequestLength="4096"
useFullyQualifiedRedirectUrl="False"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="100"
/>

The user selects a file from the local disk and the page manages to persist it to a server
location
<%@ Page language="C#"%>
<%@ Import Namespace="System.IO" %>

<script runat="server">
void UploadButton_Click(object sender, EventArgs e)
{
string savePath = UploadPath.Text.ToLower();
if (!Directory.Exists(savePath))
{
Response.Write(String.Format("<h1>The upload path doesn't exist: {0}</h1>",
savePath));
Response.End();
}
if (FileUpload1.HasFile)
{
string fileName = FileUpload1.FileName;

savePath += fileName;

FileUpload1.SaveAs(savePath);

UploadStatusLabel.Text = "File saved as: <i>" + savePath + "</i>";


}
else
{
UploadStatusLabel.Text = "You did not specify a file to upload.";
}
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>File Upload</title>
</head>
<body>
<div id="pageContent">
<form id="Form1" runat="server">
<h4>Select a picture to upload:</h4>
<b>Upload Path</b><br />
<asp:textbox id="UploadPath" runat="server" text="c:\temp\pictures\" />
<hr />
<b>Picture to upload</b><br />
<asp:fileupload id="FileUpload1" runat="server" />
<br /><br />
<asp:button id="UploadButton"
text="Upload"
onclick="UploadButton_Click"
runat="server">
</asp:button>

<hr />

<asp:label id="UploadStatusLabel" runat="server" />


</form>
</div>
</body>
</html>

1. 1. 1. Your first ASP.net page

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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

void Page_Load()
{
lblServerTime.Text = DateTime.Now.ToString();
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>First Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

The current date and time is:

<asp:Label
id="lblServerTime"
Runat="server" />

</div>
</form>
</body>
</html>

The first line contains a directive. It looks like this:

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

The code declaration block contains all the methods used in the page.
It contains all the page's functions and subroutines.

<script runat="server">

void Page_Load()
{
lblServerTime.Text = DateTime.Now.ToString();
}

</script>

1. 1. 2. The ASP.NET Framework gives you the most commonly used namespaces

System
System.Collections
System.Collections.Specialized
System.Configuration
System.Text
System.Text.RegularExpressions
System.Web
System.Web.Caching
System.Web.SessionState
System.Web.Security
System.Web.Profile
System.Web.UI
System.Web.UI.WebControls
System.Web.UI.WebControls.WebParts
System.Web.UI.HTMLControls
System.Web.Extensions
System.Xml.Linq
System.Data.DataSetExtensions
The default namespaces are listed inside the pages element in the root web configuration
file
located at the following path:

\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\Web.Config

Before you can use a class contained in an assembly in your application,


you must add a reference to the assembly.
By default, an ASP.NET application references the most common assemblies contained
in the Global Assembly Cache:

mscorlib.dll
System.dll
System.Configuration.dll
System.Web.dll
System.Data.dll
System.Web.Services.dll
System.Xml.dll
System.Drawing.dll
System.EnterpriseServices.dll
System.Web.Mobile.dll

1. 1. 3. ASP.NET reserved application folders

Folder Name Description

App_Browsers Contains browser definition files (which are XMLbased files with the
.browser extension) used by this application for
identifying and determining the capabilities of browsers.

App_Code Contains any noncodebehind class files to be used by the application.

App_Data Contains application data files, such as SQL Server Express data, Microsoft
Access files, or XML data.

App_GlobalResources Contains resource files that are available globally throughout


the application.

App_LocalResources Contains resource files that are associated with a specific page or
control.
App_Themes Contains files that define the appearance of pages and controls in the site.

App_WebReferences Contains files used to define references to external Web services.

Bin Contains compiled .NET assemblies (.DLL files).

1. 1. 4. Notable ASP.net file extension

Extension Description

.asax The Global.asax file defines application-level event handlers.

.ascx Defines a user control. User controls are used to encapsulate a block of reusable
user interface functionality.

.ashx Defines a custom HTTP handler. Handlers are used to implement custom
response functionality based on the extension of the request.

.asmx Defines an XML Web service.

.aspx Defines a Web Form.

.axd Special handlers used to manage Web site administration requests.

.config An XML-based configuration file (named Web.config) for an application or for


the machine itself (machine.config).

.master Defines a master page that specifies the common layout for other Web Forms.

.resx Resource file containing resource strings used for localization.

.sitemap Defines the navigation structure of the site.

.skin Defines the visual property settings to be applied to controls in a site's theme.

1. 2. 1. Application Directory Structure

ASP.NET defines a few directories with special meanings.


Directory Description
Bin Contains all the precompiled .NET assemblies usually DLLs

App_Code Contains source code files that are dynamically compiled for use

App_GlobalResources stores global resources


App_LocalResources resources are accessible for their dedicated page only
App_WebReferences Stores references to web services that the web application uses.
This includes WSDL files and discovery documents.

App_Data reserved for data storage

App_Browsers browser definitions stored in XML files

App_Themes themes used by the web application

1. 2. 2. ASP.NET Application Folders

\App_Code Folder stores your classes, .wsdl files, and typed datasets.
Items in this folder are automatically available to all the pages within your solution.

Because all the classes contained in this folder are built into a single assembly,
you cannot have classes of different languages sitting in the root \App_Code folder

\App_Code
Calculator.cs
AdvancedMath.vb

In order to work with multiple languages in your \App_Code folder,


you must make some changes to the folder structure and to the web.config file.

The first step is to add two new subfolders to the \App_Code folder - a \VB folder and
a \CS folder.

\App_Code
\VB
Add.vb
\CS
Subtract.cs

Structuring the web.config file


<compilation>
<codeSubDirectories>
<add directoryName="VB"></add>
<add directoryName="CS"></add>
</codeSubDirectories>
</compilation>

1. 2. 3. ASP.NET Page Directives

You can control the behavior of your ASP.NET pages by using these directives.

Here's an example of the Page directive:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"


Inherits="_Default" %>

Directives are commands that the compiler uses when the page is compiled.

Directives are simple to incorporate into your pages.

A directive is written in the following format:

<%@ [Directive] [Attribute=Value] %>

You can add more than a single attribute to your directive statements:

<%@ [Directive] [Attribute=Value] [Attribute=Value] %>

1. 2. 4. directives in ASP.NET

Directive Description
Assembly Links an assembly to the Page or user control for which it is associated.
Control For using with user controls (.ascx).
Implements Implements a specified .NET Framework interface.
Import Imports namespaces into the Page or user control.
Master Set master page. It be used only with master pages (.master).
MasterType Associates a class name to a Page in order to get at strongly typed
references.
OutputCache Controls the output caching policies of a Page or user control.
Page Enables you to specify page specific attributes and values to use when the
page parses or compiles.
PreviousPageType Enables an ASP.NET page to work with a postback from another
page in the application.
Reference Links a Page or user control to the current Page or user control.
Register Associates aliases with namespaces and class names for notation in
custom server control syntax.
1. 2. 5. @Page directive

@Page directive sets attributes and values for an ASP.NET page (.aspx).

<%@ Page Language="VB"


AutoEventWireup="false"
CodeFile="Default.aspx.vb"
Inherits="_Default" %>

1. 2. 6. Page Directives, code section and layout

<!-- Directives -->


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

<!-- Code Section -->


<script runat="server">
private void MakeUpper(object sender, EventArgs e)
{
string buf = TheString.Value;
TheResult.InnerHtml = buf.ToUpper();
}
</script>

<!-- Layout -->


<html>
<head><title>UpperCase</title></head>
<body>
<h1>Make It Upper</h1>
<form id="Form1" runat="server">
<input runat="server" id="TheString" type="text" />
<input runat="server" id="Button1" type="submit" value="Proceed..."
OnServerClick="MakeUpper" />
<hr>
<h3>Results:</h3>
<span runat="server" id="TheResult" />
</form>
</body>
</html>

1. 3. 1. code-inline model: all the code is contained within a single .aspx page

File Options Using Inline Coding File Created


Web Form .aspx file
Master Page .master file
Web User Control .ascx file
Web Service .asmx file

File: Default.aspx (VB)


<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)

Label1.Text = "Hello " & Textbox1.Text


End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Simple Page</title>
</head>
<body>
<form runat="server">
What is your name?<br />
<asp:Textbox ID="Textbox1" Runat="server"></asp:Textbox><br />
<asp:Button ID="Button1" Runat="server" Text="Submit"
OnClick="Button1_Click" />
<asp:Label ID="Label1" Runat="server"></asp:Label>
</form>
</body>
</html>

File: Default.aspx (C#)


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text = "Hello " + Textbox1.Text;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Simple Page</title>
</head>
<body>
<form runat="server">
What is your name?<br />
<asp:Textbox ID="Textbox1" Runat="server"></asp:Textbox><br />
<asp:Button ID="Button1" Runat="server" Text="Submit"
OnClick="Button1_Click" />
<asp:Label ID="Label1" Runat="server"></asp:Label>
</form>
</body>
</html>

1. 3. 2. code-behind model allows for code separation of the page's business logic from
its presentation logic

presentation logic for the page is stored in an .aspx page, whereas the logic piece is stored
in a separate class file: .aspx.vb or .aspx.cs.

File Options Using Code-Behind File Created


Web Form .aspx file
.aspx.vb or .aspx.cs file
Master Page .master file
.master.vb or .master.cs file
Web User Control .ascx file
.ascx.vb or .ascx.cs file
Web Service .asmx file
.asmx.vb or .asmx.cs file

An .aspx page that uses the ASP.NET 2.0 code-behind model (VB version)

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"


Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Simple Page</title>
</head>
<body>
<form runat="server">
What is your name?<br />
<asp:Textbox ID="Textbox1" Runat="server"></asp:Textbox><br />
<asp:Button ID="Button1" Runat="server" Text="Submit"
OnClick="Button1_Click" />
<asp:Label ID="Label1" Runat="server"></asp:Label>
</form>
</body>
</html>

A code-behind page (VB version)

Partial Class _Default


Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, _


ByVal e As System.EventArgs) Handles Button1.Click

Label1.Text = "Hello " & TextBox1.Text


End Sub
End Class

An .aspx page that uses the ASP.NET 2.0 code-behind model (C# version)

<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_aspx" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Simple Page</title>
</head>
<body>
<form runat="server">
What is your name?<br />
<asp:Textbox ID="Textbox1" Runat="server"></asp:Textbox><br />
<asp:Button ID="Button1" Runat="server" Text="Submit"
OnClick="Button1_Click" />
<asp:Label ID="Label1" Runat="server"></asp:Label>
</form>
</body>
</html>

A code-behind page (C# version)

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page


{
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Hello " + Textbox1.Text;
}
}

1. 3. 3. Use Code behind

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="FirstPageCodeBehind" %>
<!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 id="Head1" runat="server">
<title>First Page Code-Behind</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Button
id="Button1"
Text="Click Here"
OnClick="Button1_Click"
Runat="server" />

<br /><br />

<asp:Label
id="Label1"
Runat="server" />

</div>
</form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class FirstPageCodeBehind : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Click the Button";
}

protected void Button1_Click(object sender, EventArgs e)


{
Label1.Text = "Thanks!";
}
}

1. 3. 4. Code behind (VB.net)


<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"
Inherits="FirstPageCodeBehind" %>
<!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 id="Head1" runat="server">
<title>First Page Code-Behind</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Button
id="Button1"
Text="Click Here"
Runat="server" />

<br /><br />

<asp:Label
id="Label1"
Runat="server" />

</div>
</form>
</body>
</html>

File: Default.aspx.vb

Partial Class FirstPageCodeBehind


Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)


Handles Me.Load
Label1.Text = "Click the Button"
End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As


System.EventArgs) Handles Button1.Click
Label1.Text = "Thanks!"
End Sub
End Class

1. 4. 1. Expression

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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Sample Page</title>
<script runat="server">
void Page_Load()
{
messageLabel.Text = "Hello World";
}
</script>
</head>
<body>
<form runat="server">
<asp:Label id="messageLabel" runat="server" />
<%-- Declare the title as string and set it --%>
<% string Title = "This is generated by a code render block."; %>
<%= Title %>
</form>
</body>
</html>

1. 5. 1. ASP.NET File Types

File Name Description


Ends with .aspx ASP.NET web pages.
They contain the user interface.
Users request or navigate directly to one of these pages to start your web
application.

Ends with .ascx ASP.NET user controls.


User controls are similar to web pages, except that the user cannot access
these files directly.

Ends with .asmx ASP.NET web services collections of methods.


web.config XML-based configuration file for your ASP.NET application.
It includes settings for customizing security, state management, memory
management, and much more.

Global.asax Global application file.


To define global variables and react to global events.

Ends with .cs code-behind files that contain C# code.

Ends with .vb code-behind files that contain VB code.

1. 6. 1. The global.asax Application File

The global application class that's used by the global.asax file should always be stateless.

You can handle two types of events in the global.asax file:


Events that always occur for every request.
Events that occur only under certain conditions.
BeginRequest() called at the start of every request, including requests for files that aren't
web forms.
AuthenticateRequest() called before authentication is performed.
AuthorizeRequest() assigns special privileges.
ResolveRequestCache() is used in conjunction with output caching.
AcquireRequestState() is called before session-specific information is retrieved for the
client.
PreRequestHandlerExecute() is called before the appropriate HTTP handler executes the
request.
PostRequestHandlerExecute() is called just after the request is handled.
ReleaseRequestState() is called when the session-specific information is about to be
serialized from the Session collection.
UpdateRequestCache() is called before information is added to the output cache.
EndRequest() is called at the end of the request.

1. 6. 2. Some events don't fire with every request:

Start() is invoked when the application first starts up.


Start() is invoked each time a new session begins.
Error() is invoked whenever an unhandled exception occurs in the application.
End() is invoked whenever the user's session ends.
End() is invoked just before an application ends.
Disposed() is invoked after the application has been shut down.
1. 6. 3. Global application file. (C#)

Use this file to define global variables.


React to global events (such as when a web application first starts).

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

<script runat="server">

protected void Application_OnEndRequest()


{
Response.Write("<hr>This page was served at " +
DateTime.Now.ToString());
}

</script>

1. 6. 4. Appication level event handlers in global.asax

<script language="VB" runat="server">

Sub Application_Start(Sender as Object, e as EventArgs)


Application("Time") = System.DateTime.Now
End Sub

Sub Application_AcquireRequestState(Sender as Object, e as EventArgs)


Response.Write("Acquiring request session state" & "...<br>")
End Sub

Sub Application_AuthenticateRequest(Sender as Object, e as EventArgs)


Response.Write("Authenticating request...<br>")
End Sub

Sub Application_AuthorizeRequest(Sender as Object, e as EventArgs)


Response.Write("Authorizing request...<br>")
End Sub

Sub Application_PostRequestHandlerExecute(Sender as Object, e as EventArgs)


Response.Write("Request handler executed...<br>")
End Sub

Sub Application_PreRequestHandlerExecute(Sender as Object, e as EventArgs)


Response.Write("Request handler executed...<br>")
End Sub

Sub Application_PreSendRequestContent(Sender as Object, e as EventArgs)


Response.Write("Receiving request content...<br>")
End Sub

Sub Application_PreSendRequestHeaders(Sender as Object, e as EventArgs)


Response.Write("Receiving request headers...<br>")
End Sub

Sub Application_ReleaseRequestState(Sender as Object, e as EventArgs)


Response.Write("Releasing request state...<br>")
End Sub

Sub Application_ResolveRequestCache(Sender as Object, e as EventArgs)


Response.Write("Resolving request cache...<br>")
End Sub

Sub Application_UpdateRequestCache(Sender as Object, e as EventArgs)


Response.Write("Updating request cache...<br>")
End Sub

Sub Application_Error(Sender as Object, e as EventArgs)


Response.Write(Sender.Request.isAuthenticated & " is authenticating
request...<br>")
End Sub

Sub Session_Start(Sender as Object, e as EventArgs)


Response.Write("Session is starting...<br>")
End Sub

Sub Application_BeginRequest(Sender as Object, e as EventArgs)


Response.Write("<b>Process</b>")
Response.Write("Request is starting...<br>")
End Sub

Sub Application_EndRequest(Sender as Object, e as EventArgs)


Response.Write("Request is ending...<br>")
End Sub

</script>

1. 6. 5. Global.asax file can be used to track the number of page requests made for any
page.
File: Global.asax

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


<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>
<script runat="server">

private string _conString;


private SqlConnection _con;
private SqlCommand _cmdSelect;
private SqlCommand _cmdInsert;

public override void Init()


{
_conString = WebConfigurationManager.ConnectionStrings["Log"].
ConnectionString;
_con = new SqlConnection(_conString);

_cmdSelect = new SqlCommand("SELECT COUNT(*) FROM Log WHERE


Path=@Path", _con);
_cmdSelect.Parameters.Add("@Path", SqlDbType.NVarChar, 500);

_cmdInsert = new SqlCommand("INSERT Log (Path) VALUES (@Path)", _con);


_cmdInsert.Parameters.Add("@Path", SqlDbType.NVarChar, 500);
}

public int NumberOfRequests


{
get
{
int result = 0;
_cmdSelect.Parameters["@Path"].Value = Request.
AppRelativeCurrentExecutionFilePath;
try
{
_con.Open();
result = (int)_cmdSelect.ExecuteScalar();
}
finally
{
_con.Close();
}
return result;
}
}

void Application_BeginRequest(object sender, EventArgs e)


{
_cmdInsert.Parameters["@Path"].Value = Request.
AppRelativeCurrentExecutionFilePath;
try
{
_con.Open();
_cmdInsert.ExecuteNonQuery();
}
finally
{
_con.Close();
}
}
</script>

1. 6. 6. Application level action sequence

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

<script runat="server">

void Application_Start(Object sender, EventArgs e) {


}

protected void Application_OnEndRequest()


{
Response.Write("<hr>This page was served at " +DateTime.Now.ToString());
}

protected void Application_Error(Object sender, EventArgs e)


{
Response.Write("<font face=\"Tahoma\" size=\"2\" color=\"red\">");
Response.Write("Oops! Looks like an error occurred!!<hr></font>");
Response.Write("<font face=\"Arial\" size=\"2\">");
Response.Write(Server.GetLastError().Message.ToString());
Response.Write("<hr>" + Server.GetLastError().ToString());
Server.ClearError();
}
void Session_Start(Object sender, EventArgs e) {
}

void Session_End(Object sender, EventArgs e) {


}

</script>

1. 6. 7. Static application variables

File: Global.asax

<%@ Application Language="C#" ClassName="Global" %>


<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Collections.Generic" %>
<script runat="server">

private static string[] fileList;


public static string[] FileList
{
get
{
if (fileList == null)
{
fileList =
Directory.GetFiles(HttpContext.Current.Request.PhysicalApplicationPath);
}
return fileList;
}
}

private static Dictionary<string, string> metadata = new Dictionary<string, string>();


public void AddMetadata(string key, string value)
{
lock (metadata)
{
metadata[key] = value;
}
}
public string GetMetadata(string key)
{
lock (metadata)
{
return metadata[key];
}
}
</script>

File: Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="StaticApplicationVariables" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblInfo" runat="server"></asp:Label>

</div>
</form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using ASP;

public partial class StaticApplicationVariables : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder builder = new StringBuilder();
foreach (string file in Global.FileList)
{
builder.Append(file + "<br />");
}
lblInfo.Text = builder.ToString();
}
}

1. 6. 8. Override string GetVaryByCustomString in Global.asax (C#)

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

<script runat="server">

public override string GetVaryByCustomString(HttpContext context, string arg)


{
if (arg.ToLower() == "prefs ")
{
HttpCookie cookie = context.Request.Cookies["Language"];
if (cookie != null)
{
return cookie.Value;
}
}
return base.GetVaryByCustomString(context, arg);
}

void Application_Start(object sender, EventArgs e)


{
// Code that runs on application startup

void Application_End(object sender, EventArgs e)


{
// Code that runs on application shutdown

void Application_Error(object sender, EventArgs e)


{
// Code that runs when an unhandled error occurs
}

void Session_Start(object sender, EventArgs e)


{
// Code that runs when a new session is started

void Session_End(object sender, EventArgs e)


{

</script>

1. 6. 10. Log exception in Global.asax (C#)

using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;

namespace MyApp
{
public class Global : System.Web.HttpApplication
{
protected void Application_Error(Object sender, EventArgs e)
{
System.Diagnostics.EventLog myEventLog;
Exception ex=Server.GetLastError();
myEventLog=new System.Diagnostics.EventLog();
myEventLog.Log="Application";
myEventLog.Source="Default";
myEventLog.WriteEntry(ex.ToString());
myEventLog=null;
}
}
}
1. 6. 11. Log exception in Global.asax (VB)

Imports System.Web
Imports System.Web.SessionState

Public Class Global Inherits System.Web.HttpApplication


Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim myEventLog As System.Diagnostics.EventLog
Dim ex As Exception = Server.GetLastError()
myEventLog = New System.Diagnostics.EventLog()
myEventLog.Log = "Application"
myEventLog.Source = "Default"
myEventLog.WriteEntry(ex.ToString())
End Sub
End Class

1. 7. 1. Get value from query string

File: Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="QueryStringSender" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button id="cmdLarge"
runat="server"
Text="Large Text Version"
OnClick="cmd_Click">
</asp:Button>
<asp:Button id="cmdNormal" runat="server" Text="Normal Version"
OnClick="cmd_Click"></asp:Button>
<asp:Button id="cmdSmall" runat="server" Text="Small Text Version"
OnClick="cmd_Click"></asp:Button>
</div>
</form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class QueryStringSender : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void cmd_Click(object sender, EventArgs e)
{
Response.Redirect("NextPage.aspx" + "?Version=" +
((Control)sender).ID);
}
}

File: NextPage.aspx

<%@ Page Language="C#"


AutoEventWireup="true"
CodeFile="NextPage.aspx.cs"
Inherits="QueryStringRecipient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:label id="lblDate"
runat="server"
Width="528px"
Height="112px"
Font-Names="Verdana"
Font-Size="Large"
EnableViewState="False">
</asp:label>
</div>
</form>
</body>
</html>

File: NextPage.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class QueryStringRecipient : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
lblDate.Text = "The time is now:<br>" + DateTime.Now.ToString();
switch (Request.QueryString["Version"])
{
case "cmdLarge":
lblDate.Font.Size = FontUnit.XLarge;
break;
case "cmdNormal":
lblDate.Font.Size = FontUnit.Large;
break;
case "cmdSmall":
lblDate.Font.Size = FontUnit.Small;
break;
}
}
}

2. 1. 1. Use Select Case statement with String type value (VB)

<%@ Page Language="VB" %>

<script runat="server">
sub Page_Load(Sender as object, e as eventargs)
dim strClockStatus As String
strClockStatus = "AAA"

select Case strClockStatus


case "AAA", "BBB", "CCC"
Response.Write("A")
case "DDD"
Response.Write("B")
case else
Response.Write("C")
end select
end sub
</script>

<html><body>

</body></html>

2. 1. 2. Use Select case statement with integer type value (VB)

<%@ Page Language="VB" %>

<script runat="server">
sub Page_Load(Sender as object, e as eventargs)
dim intAge As integer = 7

select Case intAge


case "7"
Response.Write("That's a string!")
case 7
Response.Write("7")
case <10
Response.Write("less than 10")
end select

end sub
</script>

<html><body>

</body></html>

2. 2. 1. Get action sender text (VB.net)

<%@ Page Language="VB" %>

<script runat="server">
Sub Button_Click(Sender As Object, e As EventArgs)
Response.Write(Sender.Text)
End Sub
</script>

<html>
<body>
<form runat="server">
<asp:button id="btSubmit" Text="Submit" runat=server OnClick="Button_Click"/>
</form>
</body>
</html>

2. 2. 2. Report action trigger's text (VB)

<%@ Page Language="VB" %>

<script runat="server">
Sub Button1_Click(Sender as Object, e as EventArgs)
Label1.Text="You clicked <b>" & Sender.Text & "</b>"
end Sub
</script>

<html><body>
<form runat="server">
<asp:Button id=Button1 runat="server" Text="Button1"
onClick="Button1_Click" />

<asp:Label id=Label1 runat=server />


</form>
</body></html>

2. 2. 3. Report action trigger's text (C#)

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

<script runat="server">
void Button1_Click(Object Sender, EventArgs e) {
Label1.Text = "You clicked <b>" + ((Button)Sender).Text + "</b>";
}
</script>

<html><body>
<form runat="server">
<asp:Button id=Button1 runat="server" Text="Button1"
onClick="Button1_Click" />

<asp:Label id=Label1 runat=server />


</form>
</body></html>

2. 2. 4. Change img border stype in Input Button action (VB.net)

<%@ Page Language="VB" %>

<script runat="server">
Sub Click(Sender as Object, e as EventArgs)
select case Sender.Value
case "Left"
word_image.align = "left"
case "Right"
word_image.align = "right"
case "Center"
word_image.align = "center"
end select

Left.Style("Border-Style") = "notset"
Right.Style("Border-Style") = "notset"
Center.Style("Border-Style") = "notset"

Sender.Style("Border-Style") = "inset"
end Sub
</script>

<html><body>
<form runat="server">
<input type="Button" id="Left" runat="server"
Value="Left" OnServerClick="Click" />
<input type="Button" id="Center" runat="server"
Value="Center" OnServerClick="Click" />
<input type="Button" id="Right" runat="server"
Value="Right" OnServerClick="Click" />
</form>

<img src="http://www.java2s.com/style/logo.png" id="word_image" runat="server">


</BODY>
</HTML>

2. 3. 1. Use for each to loop through array (VB)

<%@ Page Language="VB" %>

<script runat="server">
sub Page_Load(Sender as object, e as eventargs)
dim strDay as string
dim arrWeekDays() as String = {"Monday", "Tuesday", _
"Wednesday", "Thursday", "Friday"}

For Each strDay in arrWeekDays


Response.Write(strDay & "<br>")
exit for
Next

end sub
</script>

<html><body>

</body></html>
2. 4. 1. Define and call function in asp.net page (C#)

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

<script runat="server">
void Page_Load(Object Sender, EventArgs e) {
MultiplyNumbers(8,9);

MultiplyNumbers(4,12);

MultiplyNumbers(38,23);
}

void MultiplyNumbers(int intA, int intB) {


Response.Write(intA * intB + "<br>");
}
</script>

<html><body>

</body></html>

2. 4. 2. Return value from function (VB)

<%@Page Language="VB" %>

<script runat="server">
sub Page_Load(obj as object,e as eventargs)
Response.Write(MultiplyNumbers(8,9)&"<br>")

Response.Write(MultiplyNumbers(4,12)&"<br>")

Response.Write(MultiplyNumbers(38,23)&"<br>")
end sub

function MultiplyNumbers(intA as integer,intB as integer) _


as Integer
Return intA *intB
end function
</script>
<html><body>

</body></html>

2. 4. 3. Define function

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>ASP.NET Functions</title>
<script runat="server" language="C#">

string getName()
{
return "Abc";
}

void Page_Load()
{
messageLabel.Text = getName();
}
</script>
</head>
<body>
<form runat="server">
<asp:Label id="messageLabel" runat="server" />
</form>
</body>
</html>

2. 4. 4. Create a function (VB)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>ASP.NET Functions</title>
<script runat="server" language="VB">
Function getName() As String
Return "a"
End Function

Sub Page_Load(s As Object, e As EventArgs)


messageLabel.Text = getName()
End Sub
</script>
</head>
<body>
<form runat="server">
<asp:Label id="messageLabel" runat="server" />
</form>
</body>
</html>

2. 5. 1. Use if statement with string type value (VB)

<%@ Page Language="VB" %>

<script runat="server">
sub Page_Load(Sender as object, e as eventargs)
dim MyMessage As String = "Hello"
dim MyBool As Boolean = True

if MyMessage = "Hello" then


Response.Write("True")
end if

if MyBool then
Response.Write("True")
end if
end sub
</script>

<html><body>

</body></html>

2. 5. 2. Use if statement with boolean type value (VB)


<%@ Page Language="VB" %>

<script runat="server">
sub Page_Load(Sender as object, e as eventargs)
dim MyMessage As String = "Hello"
dim MyBool As Boolean = True

if MyMessage = "Hello" then


Response.Write("True")
end if

if MyBool then
Response.Write("True")
end if
end sub
</script>

<html><body>

</body></html>

2. 5. 3. Use if and 'if else' statement with string and boolean type value (C#)

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

<script runat="server">
void Page_Load(Object Sender, EventArgs e) {
string MyMessage = "Hello";
bool MyBool = true;

if (MyMessage == "Hi" & MyBool) {


Response.Write(MyMessage);
} else if (MyMessage == "Hello") {
Response.Write("True");
} else {
Response.Write("False");
}

if (!MyBool) {
Response.Write("False");
}
}
</script>

<html><body>

</body></html>

2. 6. 1. Define and call sub module (function) in asp.net page (VB)

<%@ Page Language="VB" %>

<script runat="server">
sub Page_Load(Sender as object,e as EventArgs)
MultiplyNumbers(8,9)

MultiplyNumbers(4,12)

MultiplyNumbers(38,23)
end sub

sub MultiplyNumbers(intA as integer,intB as integer)


Response.Write(intA *intB &"<br>")
end sub
</script>

<html><body>

</body></html>

2. 6. 2. asp:Button action event calls a subroutine

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"


Inherits="Java2sPage" %>

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="output" runat="server"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>

File: Default.aspx.vb

Partial Class Java2sPage


Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)


Handles Me.Load
output.Text = String.Empty

DisplayMessage()
End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As


System.EventArgs) Handles Button1.Click
DisplayMessage()
End Sub

Private Sub DisplayMessage()


Dim i As Integer
For i = 1 To 4
output.Text &= "Welcome to my website<br />"
Next i
End Sub
End Class

2. 6. 3. Pass parameters to subroutine (VB.net)

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"


Inherits="Default" %>

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="output" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
</body>
</html>

File: Default.aspx.vb

Partial Class Default


Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)


Handles Me.Load
output.Text = String.Empty

DisplayMessage("Welcome to my website<br />")


End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As


System.EventArgs) Handles Button1.Click
DisplayMessage("Welcome to my website<br />")
End Sub

Private Sub DisplayMessage(ByVal message As String)


Dim i As Integer
For i = 1 To 4
output.Text &= message
Next i
End Sub

End Class

2. 7. 1. While loop

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Loops</title>
<script runat="server" language="C#">
void Page_Load()
{
int counter = 0;

while (counter <= 10)


{

messageLabel.Text = counter.ToString();

counter++;
}
}
</script>
</head>
<body>
<form runat="server">
<asp:Label id="messageLabel" runat="server"/>
</form>
</body>
</html>

2. 7. 2. Do while loop

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Loops</title>
<script runat="server" language="C#">
void Page_Load()
{

int counter = 0;

do
{

messageLabel.Text = counter.ToString();

counter++;
}
while (counter <= 10);
}
</script>
</head>
<body>
<form runat="server">
<asp:Label id="messageLabel" runat="server"/>
</form>
</body>
</html>

2. 7. 3. while loop (VB)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Loops</title>
<script runat="server" language="VB">
Sub Page_Load(s As Object, e As EventArgs)

Dim counter As Integer = 0

Do While counter <= 10

messageLabel.Text = counter.ToString()

counter += 1
Loop
End Sub
</script>
</head>
<body>
<form runat="server">
<asp:Label id="messageLabel" runat="server" />
</form>
</body>
</html>

2. 7. 4. Do while loop (VB)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Loops</title>
<script runat="server" language="VB">
Sub Page_Load(s As Object, e As EventArgs)

Dim counter As Integer = 0

Do

messageLabel.Text = counter.ToString()

counter += 1
Loop While counter <= 10
End Sub
</script>
</head>
<body>
<form runat="server">
<asp:Label id="messageLabel" runat="server" />
</form>
</body>
</html>

3. 1. 1. Import properties of The Label control

BackColor: change the background color of the label.


BorderColor: set the color of a border rendered around the label.
BorderStyle: display a border around the label. Possible values are NotSet, None,
Dotted, Dashed, Solid, Double, Groove, Ridge, Inset, and Outset.
BorderWidth: set the size of a border rendered around the label.
CssClass: associate a Cascading Style Sheet class with the label.
Font: set the label's font properties.
ForeColor: set the color of the content rendered by the label.
Style: assign style attributes to the label.
ToolTip: set a label's title attribute. (In Microsoft Internet Explorer, the title attribute
is displayed as a floating tooltip.)

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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

void Page_Load()
{
lblTime.Text = DateTime.Now.ToString("T");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show Label</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Label
id="lblTime"
Runat="server" />
</div>
</form>
</body>
</html>

3. 1. 2. Use asp:Label to display text message (VB.net)

<%@ Page Language="VB" %>

<script runat="server">
sub Page_Load(obj as object, e as eventargs)
lblMessage.Text = "This is my first exercise!"
end sub
</script>

<html><body>
<asp:Label id="lblMessage" runat="server"/>
</body></html>

3. 1. 3. Change asp:Label Text in page load event listener (VB.net)

<%@ Page Language="VB" %>

<script runat="server">
sub Page_Load(obj as object, e as eventargs)
lblMessage.Text = "This is my first exercise!"
end sub
</script>

<html><body>
<asp:Label id="lblMessage" runat="server"/>
</body></html>

3. 1. 4. Add style to asp:Label

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
<style rel="stylesheet" type="text/css">
body
{
font-family: Verdana, Arial, Sans-Serif;
font-size: small;
}

.heading1
{
font-weight: bold;
font-size: large;
color: lime;
}
.heading2
{
font-weight: bold;
font-size: medium;
font-style: italic;
color: #C0BA72;
}
.blockText
{
padding: 10px;
background-color: #FFFFD9;
border-style: solid;
border-width: thin;
}

</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label CssClass="heading1" ID="Label1" runat="server" Text="This Label
Uses heading1"></asp:Label>
<br />
This is sample unformatted text.<br />
&nbsp;<br />
<asp:Label CssClass="heading2" ID="Label2" runat="server" Text="This Label
Uses heading2"></asp:Label>
<br />
Here's more unformatted text.<br />
<br />
&nbsp;<div class="blockText" id="DIV1" runat="server" >
This control uses the blockText style. This control uses the blockText style. This
control uses the blockText style. This control uses the blockText style.
</div>
</div>
</form>
</body>
</html>

3. 1. 5. Label font

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head id="Head1" runat="server">
<title>ASP.NET Server Controls - Basics</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>ASP.NET Server Controls</h1>
<h2>Basics</h2>
<asp:Label ID="lblTime" runat="server" OnInit="lblTime_Init"></asp:Label>
</div>
</form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page


{
protected void lblTime_Init(object sender, EventArgs e)
{
lblTime.Font.Name = "Verdana";
lblTime.Font.Size = 20;
lblTime.Font.Underline = true;
lblTime.Font.Bold = true;
lblTime.Font.Italic = true;
lblTime.Font.Overline = true;
lblTime.Font.Strikeout = true;
lblTime.Text = DateTime.Now.ToString() + ". Font Name: " + lblTime.Font.Name;
}

3. 1. 6. Set Label through code (VB)

Page Language = 'VB'

<%@ Page Language="VB" %>

<script runat="server">
sub Page_Load(obj as object, e as eventargs)
lblMessage.Text = "Welcome to ASP.NET!"
end sub
</script>

<html>
<body>
<asp:Label id="lblMessage" runat="server"/>
</body>
</html>

3. 1. 7. Set text to Label (C#)

Page Language='C#'

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

<script runat="server">
void Page_Load(Object obj, EventArgs e) {
lblMessage.Text = "Welcome to ASP.NET!";
}
</script>

<html><body>
<asp:Label id="lblMessage" runat="server"/>
</body></html>

3. 1. 8. Format a Label with CSS

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


<!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 id="Head1" runat="server">
<style type="text/css">
div
{
padding:10px;
}
.labelStyle
{
color:red;
background-color:yellow;
border:Solid 2px Red;
}
</style>
<title>Format Label</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Label
id="lblFirst"
Text="First Label"
ForeColor="Red"
BackColor="Yellow"
BorderStyle="Solid"
BorderWidth="2"
BorderColor="red"
Runat="server" />

<br />

<asp:Label
id="lblSecond"
Text="Second Label"
CssClass="labelStyle"
Runat="server" />

</div>
</form>
</body>
</html>

3. 1. 9. Label controls are used to label the two TextBox controls.

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


<!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 id="Head1" runat="server">
<title>Label Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Label
id="lblFirstName"
Text="First Name:"
AssociatedControlID="txtFirstName"
Runat="server" />
<br />
<asp:TextBox
id="txtFirstName"
Runat="server" />

<br /><br />

<asp:Label
id="lblLastName"
Text="Last Name:"
AssociatedControlID="txtLastName"
Runat="server" />
<br />
<asp:TextBox
id="txtLastName"
Runat="server" />

</div>
</form>
</body>
</html>

3. 1. 10. Using the Label server control to provide hot-key functionality

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

<html xmlns="http://www.w3.org/1999/xhtml" >


<head id="Head1" runat="server">
<title>Label Server Control</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1"
Runat="server"
AccessKey="N"
AssociatedControlID="Textbox1">User<u>n</u>ame
</asp:Label>
<asp:Textbox ID="TextBox1" Runat="server"></asp:Textbox>
<asp:Label ID="Label2"
Runat="server"
AccessKey="P"
AssociatedControlID="Textbox2"><u>P</u>assword
</asp:Label>
<asp:Textbox ID="TextBox2" Runat="server"></asp:Textbox>
<asp:Button ID="Button1" Runat="server" Text="Submit" />
</form>
</body>
</html>

3. 1. 11. Label hot key

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Label HotKeys</title>
</head>
<body>
<form id="form1" runat="server">
<div id="container">
<h1>Using AccessKey for Controls</h1>
<asp:Label ID="labName" runat="server"
AccessKey="N" AssociatedControlID="txtName"
Text="<u>N</u>ame"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
<asp:Label ID="labMonth" runat="server"
AccessKey="M" AssociatedControlID="drpMonth"
Text="<u>M</u>onth"></asp:Label>
<asp:DropDownList ID="drpMonth" runat="server">
<asp:ListItem>January</asp:ListItem>
<asp:ListItem>February</asp:ListItem>
<asp:ListItem>March</asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>

3. 1. 12. Highlight with regular expression

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="Highlighting" %>

<!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>Sample Search Highlighting</title>
<style type="text/css">
.myPanel { margin: 8pt; width: 50%; padding 10pt; }
body { font-family: Tahoma, Arial; font-size: 10pt;}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:Panel ID="panSearch" runat="server" GroupingText="Search"
CssClass="myPanel">
Enter Search expression:
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox><br />
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click"
Text="Search" />
</asp:Panel>
<asp:Panel ID="panContent" runat="server" GroupingText="Content"
CssClass="myPanel">
<asp:Label ID="labContent" runat="server" />
</asp:Panel>
</form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Text.RegularExpressions;

public partial class Highlighting : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
labContent.Text = "Client-side validation is useful because it reduces round-trips to
the server. This provides immediate feedback to the user as well as improves server
performance. Unfortunately, client-side validation by itself is not sufficient. The user
could be using a browser that does not support scripting (that is, using an ancient browser
or has scripting turned off via the browser preferences). As well, client-side scripting is
potentially vulnerable to script exploits. These can happen when a malicious user enters a
javascript &lt;script&gt; block into a text field that can later cause harm when the entered
data is echoed back to the browser.";
}

protected void btnSearch_Click(object sender, EventArgs e)


{
Regex myreg = new Regex(txtSearch.Text, RegexOptions.IgnoreCase);

labContent.Text = myreg.Replace(labContent.Text, new


MatchEvaluator(ReplaceSearchWord));
}

public string ReplaceSearchWord(Match m)


{
return "<span style='font-weight:bold; background: yellow;'>" + m.Value +
"</span>";
}
}

3. 1. 13. Use of AssociatedControlID property on labels to bind a particular label to an


input control
<%@ Page language="C#" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Label For</title>
</head>
<body>
<div id="pageContent">
<form runat="server" id="MainForm">
<asp:Label ID="Label1" runat="server" Text="This label has no associated
control"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" />
<br />
<asp:Label ID="Label2" runat="server" Text="This label is associated with the
textbox"
AssociatedControlID="TextBox2"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" />
</form>
</div>
</body>
</html>

3. 2. 1. asp:Literal

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="Literal1"
runat="server" Text="Hello, World!"></asp:Literal></div>
</form>
</body>
</html>

3. 2. 2. Literal Control
The Literal control is similar to the Label control.
However, unlike the Label control, the Literal control does not render its content inside of
a <span> tag.

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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Page_Load()
{
ltlTitle.Text = DateTime.Now.ToString("D");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title><asp:Literal id="ltlTitle" Runat="Server" /></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Look in the title bar</h1>

</div>
</form>
</body>
</html>

3. 2. 3. The Mode property of Literal control

PassThrough: Displays the contents of the control without encoding.

Encode: Displays the contents of the control after HTML encoding the content.

Transform: Displays the contents of the control after stripping markup that is not
supported by the requesting device.

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


<!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 id="Head1" runat="server">
<title>Show Literal Mode</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Literal
id="ltlFirst"
Mode="PassThrough"
Text="<hr />"
Runat="server" />

<br /><br />

<asp:Literal
id="ltlSecond"
Mode="Encode"
Text="<hr />"
Runat="server" />

<br /><br />

<asp:Literal
id="ltlThird"
Mode="Transform"
Text="<hr />"
Runat="server" />

</div>
</form>
</body>
</html>

3. 2. 4. Use code behind to set value to asp:Literal (VB.net)

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"


Inherits="LiteralTime" %>

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:literal runat="server" ID="currentTime"></asp:literal>
</div>
</form>
</body>
</html>

File: Default.aspx.vb

Partial Class LiteralTime


Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)


Handles Me.Load
currentTime.Text = DateTime.Now
End Sub
End Class

3. 3. 1. Important properties, methods and events of Button control

AccessKey: specify a key that navigates to the Button control.

CommandArgument: specify a command argument that is passed to the Command


event.

CommandName: specify a command name that is passed to the Command event.

Enabled: disable the Button control.

OnClientClick: specify a client-side script that executes when the button is clicked.

PostBackUrl: post a form to a particular page.

TabIndex: specify the tab order of the Button control.

Text: label the Button control.

UseSubmitBehavior: use JavaScript to post a form.

Focus: set the initial form focus to the Button control.


Click: Raised when the Button control is clicked.

Command: Raised when the Button control is clicked.


The CommandName and CommandArgument are passed to this event.

3. 3. 2. Use asp:button to submit form data (VB.net)

<%@Page Language="VB" %>

<script runat="server">
Sub tbMessage_Change(Sender As Object,E As EventArgs)
lblMessage.Text = "Hello" + tbMessage.Text
End Sub
</script>

<html>
<body>
<%Response.Write("Our First Page")%>
<form runat="server">
Please enter your name:
<asp:textbox id="tbMessage" OnTextChanged="tbMessage_Change"
runat=server/>
<asp:button id="btSubmit" Text="Submit" runat=server/>
<asp:label id="lblMessage" font-size="20pt" runat=server/>
</form>
</body>
</html>

3. 3. 3. Use asp:button to trigger action (VB)

<%@ Page Language="VB" %>

<script runat="server">
Sub btAdd_Click(Sender As Object, E As EventArgs)
lblMessage.Text = "The answer is: " & Cint(tbNumber1.Text) +
Cint(tbNumber2.Text)
End Sub

Sub btSubtract_Click(Sender As Object, E As EventArgs)


lblMessage.Text = "The answer is: " & Cint(tbNumber1.Text) -
Cint(tbNumber2.Text)
End Sub

Sub btMultiply_Click(Sender As Object, E As EventArgs)


lblMessage.Text = "The answer is: " & Cint(tbNumber1.Text) *
Cint(tbNumber2.Text)
End Sub

Sub btDivide_Click(Sender As Object, E As EventArgs)


lblMessage.Text = "The answer is: " & Cint(tbNumber1.Text) /
Cint(tbNumber2.Text)
End Sub
</script>

<HTML>
<HEAD>

</HEAD>
<BODY>

<form runat="server">

Number 1: <asp:textbox id="tbNumber1" runat=server/><br>


Number 2: <asp:textbox id="tbNumber2" runat=server/>
<asp:button id="btAdd" Text=" + " OnClick="btAdd_Click" runat=server/>
<asp:button id="btSubtract" Text=" - " OnClick="btSubtract_Click" runat=server/>
<asp:button id="btMultiply" Text=" * " OnClick="btMultiply_Click" runat=server/>
<asp:button id="btDivide" Text=" / " OnClick="btDivide_Click" runat=server/>
<asp:label id="lblMessage" font-size="20pt" runat=server/>

</form>

</BODY>
</HTML>

3. 3. 4. Use asp:button to trigger action (C#)

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

<script runat="server">
void btAdd_Click(Object Sender, EventArgs e) {
lblMessage.Text = "The answer is: " + (Convert.ToInt32(tbNumber1.Text) +
Convert.ToInt32(tbNumber2.Text)).ToString();
}
void btSubtract_Click(Object Sender, EventArgs e) {
lblMessage.Text = "The answer is: " + (Convert.ToInt32(tbNumber1.Text) -
Convert.ToInt32(tbNumber2.Text)).ToString();
}

void btMultiply_Click(Object Sender, EventArgs e) {


lblMessage.Text = "The answer is: " + (Convert.ToInt32(tbNumber1.Text) *
Convert.ToInt32(tbNumber2.Text)).ToString();
}

void btDivide_Click(Object Sender, EventArgs e) {


lblMessage.Text = "The answer is: " + (Convert.ToInt32(tbNumber1.Text) /
Convert.ToInt32(tbNumber2.Text)).ToString();
}
</script>

<HTML>
<HEAD>

</HEAD>
<BODY>

<form runat="server">

Number 1: <asp:textbox id="tbNumber1" runat=server/><br>


Number 2: <asp:textbox id="tbNumber2" runat=server/>
<asp:button id="btAdd" Text=" + " OnClick="btAdd_Click" runat=server/>
<asp:button id="btSubtract" Text=" - " OnClick="btSubtract_Click" runat=server/>
<asp:button id="btMultiply" Text=" * " OnClick="btMultiply_Click" runat=server/>
<asp:button id="btDivide" Text=" / " OnClick="btDivide_Click" runat=server/>
<asp:label id="lblMessage" font-size="20pt" runat=server/>

</form>

</BODY>
</HTML>

3. 3. 5. Calcualate in button click action

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="test.aspx.vb"


Inherits="Calculator" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Your height (in inches):
<asp:TextBox ID="height" runat="server"></asp:TextBox><br />
<br />
Weight (in pounds):
<asp:TextBox ID="weight" runat="server"></asp:TextBox><br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Calculate" /><br />
<br />
<asp:Label ID="results" runat="server"></asp:Label></div>
</form>
</body>
</html>

File: test.aspx.vb

Partial Class Calculator


Inherits System.Web.UI.Page

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As


System.EventArgs) Handles btnSubmit.Click
Dim h As Integer = height.Text
Dim w As Integer = weight.Text

Dim result As Double


result = w / h

results.Text = "value is " & result

End Sub
End Class

3. 3. 6. Button Page Counter (VB.net)


<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)


Dim btn As Button = CType(sender, Button)
btn.Text = (Int32.Parse(btn.Text) + 1).ToString()
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Button Counters</title>
</head>
<body>
<form id="form1" runat="server">
<div>

First Counter:
<asp:Button
id="Button1"
Text="0"
OnClick="Button_Click"
Runat="server" />

<br /><br />

Second Counter:
<asp:Button
id="Button2"
Text="0"
OnClick="Button_Click"
Runat="server" />

</div>
</form>
</body>
</html>

3. 3. 7. Display event arguments

<%@ Page Language="VB" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub btnElephant_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
lblX.Text = e.X.ToString()
lblY.Text = e.Y.ToString()
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show EventArgs</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:ImageButton
id="btnElephant"
ImageUrl="http://www.java2s.com/style/logo.png"
OnClick="btnElephant_Click"
Runat="server" />

<br />
X Coordinate:
<asp:Label
id="lblX"
Runat="server" />
<br />
Y Coordinate:
<asp:Label
id="lblY"
Runat="server" />

</div>
</form>
</body>
</html>

3. 3. 8. Hide a controll

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="CheckBoxTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Check Box Test</title>

</head>
<body>
<form id="form1" runat="server">
<div id="container">
<h1>Check Box Test</h1>
<div class="box">
Delivery:
<asp:CheckBox ID="chkDelivery" runat="server"
OnCheckedChanged="CheckChanged" AutoPostBack="True" />
<asp:Label ID="labAddress"
runat="server"
Text="Customer Address: "
Visible="false" /><br />
<asp:TextBox ID="txtAddress"
runat="server"
Columns="60"
Visible="False" />
Pizza Styles: <br />
<asp:CheckBox ID="chkThin" runat="server" Text="Thin Crust" />
<br />
<asp:CheckBox ID="chkExtra" runat="server" Text="Extra Sauce" />
</div>

<asp:Button ID="btnOrder" runat="server"


Text="Order Pizza" OnClick="btnOrder_Click" />
<strong><asp:Label ID="labMessage" runat="server" /></strong>
</div>
</form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class CheckBoxTest : System.Web.UI.Page


{

protected void CheckChanged(object sender, System.EventArgs e)


{
if (chkDelivery.Checked)
{
txtAddress.Visible = true;
labAddress.Visible = true;
}
else
{
txtAddress.Visible = false;
labAddress.Visible = false;
}
}
protected void btnOrder_Click(object sender, EventArgs e)
{
labMessage.Text = "Pizza Order Styles: <br/>";
if (chkThin.Checked)
labMessage.Text += chkThin.Text + "<br/>"; ;
if (chkExtra.Checked)
labMessage.Text += chkExtra.Text + "<br/>"; ;
}
}

3. 3. 9. Using Client Scripts with Button Controls

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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

protected void btnDelete_Click(object sender, EventArgs e)


{
lblResult.Text = "All pages deleted!";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Button OnClientClick</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Button
id="btnDelete"
Text="Delete Website"
OnClick="btnDelete_Click"
OnClientClick="return confirm('Are you sure?');"
Runat="server" />

<br /><br />

<asp:Label
id="lblResult"
Runat="server" />

</div>
</form>
</body>
</html>

3. 3. 10. A button control with onmouseover and onmouseout setting

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


<!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 id="Head1" runat="server">
<title>Button Expando</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button
id="btnSubmit"
Text="Submit"
onmouseover="this.value='Click Here!'"
onmouseout="this.value='Submit'"
Runat="server" />
</div>
</form>
</body>
</html>

3. 3. 11. Annonymous delegate as the event handler

<%@ page language="C#" %>

<script runat="server">
void Page_Load (object sender, System.EventArgs e) {
string text = "Yeah, you clicked the button!";

this.Button1.Click += delegate(object dlgSender, EventArgs dlgE) {


Label1.Text = text;
};
}
</script>

<html>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form runat="server">
<asp:button id="Button1" runat="server" text="Button" />
<br />
<br />
<asp:label id="Label1" runat="server">Please click da button!</asp:label>

</form>
</body>
</html>

3. 3. 12. Add event handler to a button in page load event

<%@ page language="C#" %>

<script runat="server">
void Page_Load (object sender, System.EventArgs e) {

this.Button1.Click += delegate(object dlgSender, EventArgs dlgE) {


Label1.Text = "Yeah, you clicked the button!";
};
}
</script>

<html>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form runat="server">
<asp:button id="Button1" runat="server" text="Button" />
<br />
<br />
<asp:label id="Label1" runat="server">click button!</asp:label>

</form>
</body>
</html>

3. 3. 13. UseSubmitBehavior Property

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>UseSubmitBehavior Property</title>
</head>
<body>
<form id="form1" runat="server">
<div id="pageContent">
<asp:Button ID="Button1" runat="server" Text="Click here"
UseSubmitBehavior="false" />
</div>
</form>
</body>
</html>

Anda mungkin juga menyukai