Vous êtes sur la page 1sur 30

ASP.NET Tutorial - with ASP.NET 2.

Link Convert to C# : http://labs.developerfusion.co.uk/convert/vb-to-csharp.aspx


ASP.NET Introduction
ASP.NET is the latest version of Microsoft's Active Server Pages technology (ASP).

What is ASP.NET?

ASP.NET is a server side scripting technology that enables scripts (embedded in web pages) to be executed by an Internet server.

•ASP.NET is a Microsoft Technology


•ASP stands for Active Server Pages
•ASP.NET is a program that runs inside IIS
•IIS (Internet Information Services) is Microsoft's Internet server
•IIS comes as a free component with Windows servers
•IIS is also a part of Windows 2000 and XP Professional

What is an ASP.NET File?

•An ASP.NET file is just the same as an HTML file


•An ASP.NET file can contain HTML, XML, and scripts
•Scripts in an ASP.NET file are executed on the server
•An ASP.NET file has the file extension ".aspx"

How Does ASP.NET Work?

•When a browser requests an HTML file, the server returns the file
•When a browser requests an ASP.NET file, IIS passes the request to the ASP.NET engine on the server
•The ASP.NET engine reads the file, line by line, and executes the scripts in the file
•Finally, the ASP.NET file is returned to the browser as plain HTML

What is ASP+?

ASP+ is the same as ASP.NET.

ASP+ is just an early name used by Microsoft when they developed ASP.NET.

The Microsoft .NET Framework

The .NET Framework is the infrastructure for the Microsoft .NET platform.

The .NET Framework is an environment for building, deploying, and running Web applications and Web Services.

Microsoft's first server technology ASP (Active Server Pages), was a powerful and flexible "programming language". But it was too code oriented. It
was not an application framework and not an enterprise development tool.
The Microsoft .NET Framework was developed to solve this problem.

The .NET Framework consists of 3 main parts:

Programming languages:

•C# (Pronounced C sharp)


•Visual Basic (VB .NET)
•J# (Pronounced J sharp)

Server technologies and client technologies:

•ASP .NET (Active Server Pages)


•Windows Forms (Windows desktop solutions)
•(PDA / Mobile solutions)

Development environments:

•Visual Studio .NET (VS .NET)


•Visual Web Developer

ASP.NET 2.0

ASP.NET 2.0 improves upon ASP.NET by adding support for several new features.

You can read more about the differences between ASP.NET 2.0 and ASP.NET in the next chapter of this tutorial.

ASP.NET 3.0

ASP.NET 3.0 is not a new version of ASP.NET. It's just the name for a new ASP.NET 2.0 framework library with support for Windows Presentation
Foundation, Windows Communication Foundation, Windows Workflow Foundation; and Windows CardSpace.

Language Support

ASP.NET uses the new ADO.NET.

ASP.NET supports full Visual Basic, not VBScript.

ASP.NET supports C# (C sharp) and C++.

ASP.NET supports JScript as before.


ASP.NET Controls

ASP.NET contains a large set of HTML controls. Almost all HTML elements on a page can be defined as ASP.NET control objects that can be controlled
by scripts.

ASP.NET also contains a new set of object oriented input controls, like programmable list boxes and validation controls.

A new data grid control supports sorting, data paging, and everything you expect from a dataset control.

Event Aware Controls

All ASP.NET objects on a Web page can expose events that can be processed by ASP.NET code.

Load, Click and Change events handled by code makes coding much simpler and much better organized.

User Authentication

ASP.NET supports forms-based user authentication, including cookie management and automatic redirecting of unauthorized logins.

(You can still do your custom login page and custom user checking).

User Accounts and Roles

AS .NET allows for user accounts and roles, to give each user (with a given role) access to different server code and executables.

Web Server Controls


Web Server Control Description

Displays a sequence of images


AdRotator

Button Displays a push button

Calendar Displays a calendar

CalendarDay A day in a calendar control

Displays a check box


CheckBox

Creates a multi-selection check box group


CheckBoxList
DataGrid Displays fields of a data source in a grid

DataList Displays items from a data source by using templates

Creates a drop-down list


DropDownList

Creates a hyperlink
HyperLink

Displays an image
Image

Image Button Displays a clickable image

Label Displays static content which is programmable (lets you apply styles to its content)

Creates a hyperlink button


LinkButton

Creates a single- or multi-selection drop-down list


ListBox

Creates an item in a list


ListItem

Displays static content which is programmable(does not let you apply styles to its
Literal content)

Provides a container for other controls


Panel

Reserves space for controls added by code


PlaceHolder

Creates a radio button


RadioButton

Creates a group of radio buttons


RadioButtonList

Creates a list in bullet format


BulletedList

Repeater Displays a repeated list of items bound to the control

Sets the style of controls


Style

Creates a table
Table

Creates a table cell


TableCell

Creates a table row


TableRow

Creates a text box


TextBox

Displays an XML file or the results of an XSL transform


Xml
Dynamic Page in ASP .NET

This following code displays our example as an ASP.NET page:

<html>
<body bgcolor="yellow">
<center>
<h2>Hello!</h2>
<p><%Response.Write(now())%></p>
</center>
</body>
</html>

create an event handler for the Click event which changes the text on the button:

<script runat="server">
public void submit(object Source, EventArgs e)
{
button1.Text = "You clicked me!";
}

</script>
<html>
<body>
<form runat="server">
<asp:Button id="button1" Text="Click me!"
runat="server" OnClick="submit"/>
</form>
</body>
</html>

The Page_Load Event

The Page_Load event is one of many events that ASP.NET understands. The Page_Load event is triggered when a page loads, and ASP.NET will
automatically call the subroutine Page_Load, and execute the code inside it:

<script runat="server">
public void Page_Load()
{

lbl1.Text = "The date and time is " + now();

}
</script>
<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
</form>
</body>
</html>

Note: The Page_Load event contains no object references or event arguments!


The Page.IsPostBack Property

The Page_Load subroutine runs EVERY time the page is loaded. If you want to execute the code in the Page_Load subroutine only the FIRST time
the page is loaded, you can use the Page.IsPostBack property. If the Page.IsPostBack property is false, the page is loaded for the first time, if it is
true, the page is posted back to the server (i.e. from a button click on a form):

<script runat="server">
public void Page_Load()
{

if (!Page.IsPostBack) {

lbl1.Text = "The date and time is " + now();

}
public void Submit(object s, EventArgs e)
{

lbl2.Text = "Hello World!";

}
</script>
<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
<h3><asp:label id="lbl2" runat="server" /></h3>
<asp:button text="Submit" onclick="submit" runat="server" />
</form>
</body>
</html>

Maintaining the ViewState

Look at the following .aspx file. It demonstrates the "old" way to do it. When you click on the submit button, the form value will disappear:

<html>
<body>
<form action="demo_classicasp.aspx" method="post">
Your name: <input type="text" name="fname" size="20">
<input type="submit" value="Submit">
</form>
<%
object fname;

fname = Request.Form("fname");

if (fname != "") {

Response.Write("Hello " + fname + "!");

}
%>
</body>
</html>

Here is the new ASP .NET way. When you click on the submit button, the form value will NOT disappear:
<script runat="server">
public void submit(object sender, EventArgs e)
{

lbl1.Text = "Hello " + txt1.Text + "!";

}
</script>
<html>
<body>
<form runat="server">
Your name: <asp:TextBox id="txt1" runat="server" />
<asp:Button OnClick="submit" Text="Submit" runat="server" />
<p><asp:Label id="lbl1" runat="server" /></p>
</form>
</body>
</html>

The TextBox Control

Example

<html>
<body>

<form runat="server">

A basic TextBox:
<asp:TextBox id="tb1" runat="server" />
<br /><br />

A password TextBox:
<asp:TextBox id="tb2" TextMode="password" runat="server" />
<br /><br />

A TextBox with text:


<asp:TextBox id="tb4" Text="Hello World!" runat="server" />
<br /><br />

A multiline TextBox:
<asp:TextBox id="tb3" TextMode="multiline" runat="server" />
<br /><br />

A TextBox with height:


<asp:TextBox id="tb6" rows="5" TextMode="multiline"
runat="server" />
<br /><br />

A TextBox with width:


<asp:TextBox id="tb5" columns="30" runat="server" />

</form>

</body>
</html>

AUTOPOSTBACK
<script runat="server">
public void change(object sender, EventArgs e)
{

lbl1.Text = "You changed text to " + txt1.Text;

}
</script>
<html>
<body>
<form runat="server">
Enter your name:
<asp:TextBox id="txt1" runat="server"
text="Hello World!"
ontextchanged="change" autopostback="true"/>
<p><asp:Label id="lbl1" runat="server" /></p>
</form>
</body>
</html>

Validation Server Controls

A Validation server control is used to validate the data of an input control. If the data does not pass validation, it will display an error message to the
user.

The syntax for creating a Validation server control is:

<asp:control_name id="some_id" runat="server" />

Validation Server Control Description

CompareValidator Compares the value of one input control to the value of another input
control or to a fixed value

CustomValidator Allows you to write a method to handle the validation of the value
entered

RangeValidator Checks that the user enters a value that falls between two values

RegularExpressionValidator Ensures that the value of an input control matches a specified pattern

RequiredFieldValidator Makes an input control a required field

ValidationSummary Displays a report of all validation errors occurred in a Web page

Compare Validator

<html>
<body>
<form runat="server">
<table border="0" bgcolor="#b0c4de">
<tr valign="top">
<td colspan="4"><h4>Compare two values</h4></td>
</tr>
<tr valign="top">
<td><asp:TextBox id="txt1" runat="server" /></td>
<td> = </td>
<td><asp:TextBox id="txt2" runat="server" /></td>
<td><asp:Button Text="Validate" runat="server" /></td>
</tr>
</table>
<br />
<asp:CompareValidator
id="compval"
Display="dynamic"
ControlToValidate="txt1"
ControlToCompare="txt2"
ForeColor="red"
BackColor="yellow"
Type="String"
EnableClientScript="false"
Text="Validation Failed!"
runat="server" />
</form>

</body>
</html>

CustomValidator

<script runat="server">
public void user(object source, ServerValidateEventArgs args)
{
if (Strings.len(args.Value) < 8 | Strings.len(args.Value) > 16) {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
</script>

<html>
<body>

<form runat="server">
<asp:Label runat="server" Text="Enter a username: " />
<asp:TextBox id="txt1" runat="server" />
<asp:Button Text="Submit" runat="server"/>
<br />
<asp:Label id="mess" runat="server"/>
<br />
<asp:CustomValidator
ControlToValidate="txt1"
OnServerValidate="user"
Text="A username must be between 8 and 16 characters!"
runat="server"/>
</form>
</body>
</html>

Range Validator

<html>
<body>

<form runat="server">
Enter a date between 2005-01-01 and 2005-12-31:
<br />
<asp:TextBox id="tbox1" runat="server" />
<br /><br />
<asp:Button Text="Submit" runat="server" />
<br /><br />
<asp:RangeValidator
ControlToValidate="tbox1"
MinimumValue="2005-01-01"
MaximumValue="2005-12-31"
Type="Date"
EnableClientScript="false"
Text="The date must be between 2005-01-01 and 2005-12-31!"
runat="server" />
</form>

</body>
</html>

RegularExpression Validator

<script runat="server">
public void submit(object sender, EventArgs e)
{
if (Page.IsValid) {
lbl.Text = "The page is valid!";
}
else {
lbl.Text = "The page is not valid!";
}
}
</script>

<html>
<body>

<form runat="server">
Enter a US zip code:
<asp:TextBox id="txtbox1" runat="server" />
<br /><br />
<asp:Button text="Submit" OnClick="submit" runat="server" />
<br /><br />
<asp:Label id="lbl" runat="server" />
<br />
<asp:RegularExpressionValidator
ControlToValidate="txtbox1"
ValidationExpression="\d{5}"
EnableClientScript="false"
ErrorMessage="The zip code must be 5 numeric digits!"
runat="server" />
</form>

</body>
</html>

RequiredFieldValidator Control

<html>
<body>

<form runat="server">
Name: <asp:TextBox id="name" runat="server" />
<br />
Age: <asp:TextBox id="age" runat="server" />
<br /><br />
<asp:Button runat="server" Text="Submit" />
<br /><br />
<asp:RequiredFieldValidator
ControlToValidate="name"
Text="The name field is required!"
runat="server" />
</form>

</body>
</html>

ValidationSummary Control

<html>
<body>

<form runat="server">
<table>
<tr>
<td>
<table bgcolor="#b0c4de" cellspacing="10">
<tr>
<td align="right">Name:</td>
<td><asp:TextBox id="txt_name" runat="server"/></td>
<td>
<asp:RequiredFieldValidator
ControlToValidate="txt_name"
ErrorMessage="Name"
Text="*"
runat="server"/>
</td>
</tr>
<tr>
<td align="right">Card Type:</td>
<td>
<asp:RadioButtonList id="rlist_type"
RepeatLayout="Flow"
runat="server">
<asp:ListItem>Diners</asp:ListItem>
<asp:ListItem>MasterCard</asp:ListItem>
<asp:ListItem>Visa</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:RequiredFieldValidator
ControlToValidate="rlist_type"
ErrorMessage="Card Type"
InitialValue=""
Text="*"
runat="server"/>
</td>
</tr>
<tr>
<td></td>
<td><asp:Button id="b1" Text="Submit" runat="server"/></td>
<td></td>
</tr>
</table>
</td>
</tr>
</table>
<br />
<asp:ValidationSummary
HeaderText="You must enter a value in the following fields:"
DisplayMode="BulletList"
EnableClientScript="true"
runat="server"/>
</form>

</body>
</html>

Data Binding

The following controls are list controls which support data binding:

•asp:RadioButtonList
•asp:CheckBoxList
•asp:DropDownList
•asp:Listbox

The selectable items in each of the above controls are usually defined by one or more asp:ListItem controls, like this:

<html>
<body>
<form runat="server">
<asp:RadioButtonList id="countrylist" runat="server">
<asp:ListItem value="N" text="Norway" />
<asp:ListItem value="S" text="Sweden" />
<asp:ListItem value="F" text="France" />
<asp:ListItem value="I" text="Italy" />
</asp:RadioButtonList>
</form>
</body>
</html>
Create an ArrayList

The ArrayList object is a collection of items containing a single data value.

Items are added to the ArrayList with the Add() method.

The following code creates a new ArrayList object named mycountries and four items are added:

<script runat="server">
public void Page_Load()
{

if (!Page.IsPostBack) {

object mycountries = new ArrayList();

mycountries.Add("Norway");

mycountries.Add("Sweden");

mycountries.Add("France");

mycountries.Add("Italy");

}
</script>

By default, an ArrayList object contains 16 entries. An ArrayList can be sized to its final size with the TrimToSize() method:

<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New ArrayList
mycountries.Add("Norway")
mycountries.Add("Sweden")
mycountries.Add("France")
mycountries.Add("Italy")
mycountries.TrimToSize()
end if
end sub
</script>

An ArrayList can also be sorted alphabetically or numerically with the Sort() method:
<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New ArrayList
mycountries.Add("Norway")
mycountries.Add("Sweden")
mycountries.Add("France")
mycountries.Add("Italy")
mycountries.TrimToSize()
mycountries.Sort()
end if
end sub
</script>

To sort in reverse order, apply the Reverse() method after the Sort() method:

<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New ArrayList
mycountries.Add("Norway")
mycountries.Add("Sweden")
mycountries.Add("France")
mycountries.Add("Italy")
mycountries.TrimToSize()
mycountries.Sort()
mycountries.Reverse()
end if
end sub
</script>

Data Binding to an ArrayList

An ArrayList object may automatically generate the text and values to the following controls:

•asp:RadioButtonList
•asp:CheckBoxList
•asp:DropDownList
•asp:Listbox

To bind data to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .aspx page:

<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server" />
</form>
</body>
</html>

Then add the script that builds the list and binds the values in the list to the RadioButtonList control:
<script runat="server">
public void Page_Load()
{

if (!Page.IsPostBack) {

object mycountries = new ArrayList();

mycountries.Add("Norway");

mycountries.Add("Sweden");

mycountries.Add("France");

mycountries.Add("Italy");

mycountries.TrimToSize();

mycountries.Sort();

rb.DataSource = mycountries;

rb.DataBind();

}
</script>
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server" />
</form>
</body>
</html>

Create a Hashtable

The Hashtable object contains items in key/value pairs. The keys are used as indexes, and very quick searches can be made for values by searching
through their keys.

Items are added to the Hashtable with the Add() method.

The following code creates a Hashtable named mycountries and four elements are added:
<script runat="server">
public void Page_Load()
{

if (!Page.IsPostBack) {

object mycountries = new Hashtable();

mycountries.Add("N", "Norway");

mycountries.Add("S", "Sweden");

mycountries.Add("F", "France");

mycountries.Add("I", "Italy");

}
</script>

Data Binding

A Hashtable object may automatically generate the text and values to the following controls:

•asp:RadioButtonList
•asp:CheckBoxList
•asp:DropDownList
•asp:Listbox

To bind data to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .aspx page:

<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" />
</form>
</body>
</html>

Then add the script that builds the list:


<script runat="server">
public void Page_Load()
{

if (!Page.IsPostBack) {

object mycountries = new Hashtable();

mycountries.Add("N", "Norway");

mycountries.Add("S", "Sweden");

mycountries.Add("F", "France");

mycountries.Add("I", "Italy");

rb.DataSource = mycountries;
rb.DataValueField = "Key";
rb.DataTextField = "Value";
rb.DataBind();

}
</script>
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" />
</form>
</body>
</html>

Then we add a sub routine to be executed when the user clicks on an item in the RadioButtonList control. When a radio button is clicked, a text will
appear in a label:
<script runat="server">
public void Page_Load()
{

if (!Page.IsPostBack) {

object mycountries = new Hashtable();

mycountries.Add("N", "Norway");

mycountries.Add("S", "Sweden");

mycountries.Add("F", "France");

mycountries.Add("I", "Italy");

rb.DataSource = mycountries;

rb.DataValueField = "Key";

rb.DataTextField = "Value";

rb.DataBind();

}
public void displayMessage(object s, EventArgs e)
{

lbl1.text = "Your favorite country is: " + rb.SelectedItem.Text;

}
</script>
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
<p><asp:label id="lbl1" runat="server" /></p>
</form>
</body>
</html>

We can bind an XML file to a list control.


An XML File

Here is an XML file named "countries.xml":


<?xml version="1.0" encoding="ISO-8859-1"?>
<countries>
<country>
<text>Norway</text>
<value>N</value>
</country>
<country>
<text>Sweden</text>
<value>S</value>
</country>
<country>
<text>France</text>
<value>F</value>
</country>
<country>
<text>Italy</text>
<value>I</value>
</country>
</countries>

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


<script runat="server">
public void Page_Load()
{

if (!Page.IsPostBack) {

object mycountries = new DataSet();

mycountries.ReadXml(MapPath("countries.xml"));

rb.DataSource = mycountries;

rb.DataValueField = "value";

rb.DataTextField = "text";

rb.DataBind();

</script>
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
</form>
</body>
</html>

Bind a DataSet to a Repeater Control

We will use the following XML file in our examples ("cdcatalog.xml"):


<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
<cd>
<title>Greatest Hits</title>
<artist>Dolly Parton</artist>
<country>USA</country>
<company>RCA</company>
<price>9.90</price>
<year>1982</year>
</cd>
<cd>
<title>Still got the blues</title>
<artist>Gary Moore</artist>
<country>UK</country>
<company>Virgin records</company>
<price>10.20</price>
<year>1990</year>
</cd>
<cd>
<title>Eros</title>
<artist>Eros Ramazzotti</artist>
<country>EU</country>
<company>BMG</company>
<price>9.90</price>
<year>1997</year>
</cd>
</catalog>

First, import the "System.Data" namespace. We need this namespace to work with DataSet objects. Include the following directive at the top of an
.aspx page:

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


<%@ Import Namespace="System.Data" %>
<script runat="server">
public void Page_Load()
{

if (!Page.IsPostBack) {

object mycdcatalog = new DataSet();

mycdcatalog.ReadXml(MapPath("cdcatalog.xml"));

cdcatalog.DataSource = mycdcatalog;

cdcatalog.DataBind();

}
</script>
<html>
<body>
<form runat="server">
<asp:Repeater id="cdcatalog" runat="server">
<HeaderTemplate>
<table border="1" width="100%">
<tr>
<th>Title</th>
<th>Artist</th>
<th>Country</th>
<th>Company</th>
<th>Price</th>
<th>Year</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Container.DataItem("title")%></td>
<td><%#Container.DataItem("artist")%></td>
<td><%#Container.DataItem("country")%></td>
<td><%#Container.DataItem("company")%></td>
<td><%#Container.DataItem("price")%></td>
<td><%#Container.DataItem("year")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>

Using the <AlternatingItemTemplate>

You can add an <AlternatingItemTemplate> element after the <ItemTemplate> element to describe the appearance of alternating rows of output. In
the following example each other row in the table will be displayed in a light grey color:
<%@ Import Namespace="System.Data" %>
<script runat="server">
public void Page_Load()
{

if (!Page.IsPostBack) {

object mycdcatalog = new DataSet();

mycdcatalog.ReadXml(MapPath("cdcatalog.xml"));

cdcatalog.DataSource = mycdcatalog;

cdcatalog.DataBind();

}
</script>
<html>
<body>
<form runat="server">
<asp:Repeater id="cdcatalog" runat="server">
<HeaderTemplate>
<table border="1" width="100%">
<tr>
<th>Title</th>
<th>Artist</th>
<th>Country</th>
<th>Company</th>
<th>Price</th>
<th>Year</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Container.DataItem("title")%></td>
<td><%#Container.DataItem("artist")%></td>
<td><%#Container.DataItem("country")%></td>
<td><%#Container.DataItem("company")%></td>
<td><%#Container.DataItem("price")%></td>
<td><%#Container.DataItem("year")%></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr bgcolor="#e8e8e8">
<td><%#Container.DataItem("title")%></td>
<td><%#Container.DataItem("artist")%></td>
<td><%#Container.DataItem("country")%></td>
<td><%#Container.DataItem("company")%></td>
<td><%#Container.DataItem("price")%></td>
<td><%#Container.DataItem("year")%></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>

Using the <SeparatorTemplate>

The <SeparatorTemplate> element can be used to describe a separator between each record. The following example inserts a horizontal line
between each table row:
<%@ Import Namespace="System.Data" %>
<script runat="server">
public void Page_Load()
{

if (!Page.IsPostBack) {

object mycdcatalog = new DataSet();

mycdcatalog.ReadXml(MapPath("cdcatalog.xml"));

cdcatalog.DataSource = mycdcatalog;

cdcatalog.DataBind();

}
</script>
<html>
<body>
<form runat="server">
<asp:Repeater id="cdcatalog" runat="server">
<HeaderTemplate>
<table border="0" width="100%">
<tr>
<th>Title</th>
<th>Artist</th>
<th>Country</th>
<th>Company</th>
<th>Price</th>
<th>Year</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Container.DataItem("title")%></td>
<td><%#Container.DataItem("artist")%></td>
<td><%#Container.DataItem("country")%></td>
<td><%#Container.DataItem("company")%></td>
<td><%#Container.DataItem("price")%></td>
<td><%#Container.DataItem("year")%></td>
</tr>
</ItemTemplate>
<SeparatorTemplate>
<tr>
<td colspan="6"><hr /></td>
</tr>
</SeparatorTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>

The DataList Control


<%@ Import Namespace="System.Data" %>
<script runat="server">
public void Page_Load()
{

if (!Page.IsPostBack) {

object mycdcatalog = new DataSet();

mycdcatalog.ReadXml(MapPath("cdcatalog.xml"));

cdcatalog.DataSource = mycdcatalog;

cdcatalog.DataBind();

}
</script>
<html>
<body>
<form runat="server">
<asp:DataList id="cdcatalog"
gridlines="both" runat="server">
<HeaderTemplate>
My CD Catalog
</HeaderTemplate>
<ItemTemplate>
"<%#Container.DataItem("title")%>" of
<%#Container.DataItem("artist")%> -
$<%#Container.DataItem("price")%>
</ItemTemplate>
<FooterTemplate>
Copyright Hege Refsnes
</FooterTemplate>
</asp:DataList>
</form>
</body>
</html>

Using Styles
You can also add styles to the DataList control to make the output more fancy:
<%@ Import Namespace="System.Data" %>
<script runat="server">
public void Page_Load()
{

if (!Page.IsPostBack) {

object mycdcatalog = new DataSet();

mycdcatalog.ReadXml(MapPath("cdcatalog.xml"));

cdcatalog.DataSource = mycdcatalog;

cdcatalog.DataBind();

}
</script>
<html>
<body>
<form runat="server">
<asp:DataList id="cdcatalog"
runat="server"
cellpadding="2"
cellspacing="2"
borderstyle="inset"
backcolor="#e8e8e8"
width="100%"
headerstyle-font-name="Verdana"
headerstyle-font-size="12pt"
headerstyle-horizontalalign="center"
headerstyle-font-bold="true"
itemstyle-backcolor="#778899"
itemstyle-forecolor="#ffffff"
footerstyle-font-size="9pt"
footerstyle-font-italic="true">
<HeaderTemplate>
My CD Catalog
</HeaderTemplate>
<ItemTemplate>
"<%#Container.DataItem("title")%>" of
<%#Container.DataItem("artist")%> -
$<%#Container.DataItem("price")%>
</ItemTemplate>
<FooterTemplate>
Copyright Hege Refsnes
</FooterTemplate>
</asp:DataList>
</form>
</body>
</html>

ASP.NET - Database Connection


ADO.NET is also a part of the .NET Framework. ADO.NET is used to handle data access. With ADO.NET
you can work with databases.

What is ADO.NET?

•ADO.NET is a part of the .NET Framework


•ADO.NET consists of a set of classes used to handle data access
•ADO.NET is entirely based on XML
•ADO.NET has, unlike ADO, no Recordset object

Create a Database Connection

We are going to use the Northwind database in our examples.

First, import the "System.Data.OleDb" namespace. We need this namespace to work with Microsoft Access and other OLE DB database providers.
We will create the connection to the database in the Page_Load subroutine. We create a dbconn variable as a new OleDbConnection class with a
connection string which identifies the OLE DB provider and the location of the database. Then we open the database connection:

<%@ Import Namespace="System.Data.OleDb" %>


<script runat="server">
sub Page_Load
dim dbconn
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
data source=" & server.mappath("northwind.mdb"))
dbconn.Open()
end sub
</script>

Note: The connection string must be a continuous string without a line break!

Create a Database Command

To specify the records to retrieve from the database, we will create a dbcomm variable as a new OleDbCommand class. The OleDbCommand class is
for issuing SQL queries against database tables:

<%@ Import Namespace="System.Data.OleDb" %>


<script runat="server">
public void Page_Load()
{

object dbconn;
object sql;
object dbcomm;

dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source="


+ server.mappath("northwind.mdb"));

dbconn.Open();

sql = "SELECT * FROM customers";

dbcomm = new OleDbCommand(sql, dbconn);

}
</script>

Create a DataReader

The OleDbDataReader class is used to read a stream of records from a data source. A DataReader is created by calling the ExecuteReader method of
the OleDbCommand object:
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
public void Page_Load()
{

object dbconn;
object sql;
object dbcomm;
object dbread;

dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source="


+ server.mappath("northwind.mdb"));

dbconn.Open();

sql = "SELECT * FROM customers";

dbcomm = new OleDbCommand(sql, dbconn);

dbread = dbcomm.ExecuteReader();

</script>

Bind to a Repeater Control

Then we bind the DataReader to a Repeater control:


<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
public void Page_Load()
{

object dbconn;
object sql;
object dbcomm;
object dbread;

dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source="


+ server.mappath("northwind.mdb"));

dbconn.Open();

sql = "SELECT * FROM customers";

dbcomm = new OleDbCommand(sql, dbconn);

dbread = dbcomm.ExecuteReader();

customers.DataSource = dbread;

customers.DataBind();

dbread.Close();

dbconn.Close();

}
</script>
<html>
<body>
<form runat="server">
<asp:Repeater id="customers" runat="server">
<HeaderTemplate>
<table border="1" width="100%">
<tr>
<th>Companyname</th>
<th>Contactname</th>
<th>Address</th>
<th>City</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Container.DataItem("companyname")%></td>
<td><%#Container.DataItem("contactname")%></td>
<td><%#Container.DataItem("address")%></td>
<td><%#Container.DataItem("city")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>

Close the Database Connection

Always close both the DataReader and database connection after access to the database is no longer required:
dbread.Close()
dbconn.Close()

Master Pages
Master pages provide templates for other pages on your web site.

Master Pages

Master pages allow you to create a consistent look and behavior for all the pages (or group of pages) in your web application.

A master page provides a template for other pages, with shared layout and functionality. The master page defines placeholders for the content,
which can be overridden by content pages. The output result is a combination of the master page and the content page.

The content pages contains the content you want to display.

When users request the content page, ASP.NET merges the pages to produce output that combines the layout of the master page with the content of
the content page.