ASP.NET Webform Introduction

ASP.Net is a server side web development technology, which provides a RAD rapid application programming model and services required to build up Microsoft based robust web and mobile application .

What is Server Side development?


Code written for asp.net technology needs server to run. ypu can't just run your by opening it in browser like html or javascript runs

ASP.Net works on top of the HTTP protocol and uses the HTTP Verbs/commands and policies to set a browser-to-server two-way communication and cooperation. ASP.Net is a server side technology of .Net platform. ASP.Net applications are complied codes, written using the extensible and reusable components or objects present in .Net framework. Asp.net application code can use the entire web hierarchy of classes during development. Code can be written in either of the following languages:

  1. C#
  2. Visual Basic .Net
  3. Jscript
  4. J#

ASP.Net consists of a large number of READYMADE controls like text boxes, buttons and labels for assembling, configuring and manipulating code to create HTML pages. ASP.Net Web Forms Model: ASP.Net web forms extend the event-driven model of interaction to the web applications. The browser submits a web form to the web server and the server returns a full markup page or HTML page in response. All client side user activities are forwarded to the server for stateful processing. The server processes the output of the client actions and triggers the reactions. Now, HTTP is a stateless protocol. ASP.Net framework helps in storing the information regarding the state of the application, which consists of:

  1. Page state
  2. Session state

The page state is the state of the client, i.e., the content of various input fields in the web form. The session state is the collective obtained from various pages the user visited and worked with, i.e., the overall session state. To clear the concept, let us take up an example of a shopping cart as follows. User adds items to a shopping cart. Items are selected from a page, say the items page, and the total collected items and price are shown in a different page, say the cart page. Only HTTP cannot keep track of all the information coming from various pages. ASP.Net session state and server side infrastructure keeps track of the information collected globally over a session. The ASP.Net runtime carries the page state to and from the server across page requests while generating the ASP.Net runtime codes and incorporates the state of the server side components in hidden fields. This way the server becomes aware of the overall application state and operates in a two-tiered connected way.

HTTP Protocol

As we all know that HTTP is a stateless protocol uses cookies, sessions to maintain its state. If this is so then question comes into the mind that Where is ViewState in picture? we will cover story of Viewstate next

ASP.NET Features

  1. Server Controls

    ASP.NET Web server controls are objects on ASP.NET Web pages that run when the page is requested and that render markup to the browser. Many Web server controls are similar to familiar HTML elements, such as buttons and text boxes. Other controls encompass complex behavior, such as a calendar controls, and controls that you can use to connect to data sources and display data.
  2. Master Pages

    ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.
  3. Working with Data

    ASP.NET provides many options for storing, retrieving, and displaying data. In an ASP.NET Web Forms application, you use data-bound controls to automate the presentation or input of data in web page UI elements such as tables and text boxes and drop-down lists.
  4. Membership

    ASP.NET Identity stores your users’ credentials in a database created by the application. When your users log in, the application validates their credentials by reading the database. Your project's Account folder contains the files that implement the various parts of membership: registering, logging in, changing a password, and authorizing access. Additionally, ASP.NET Web Forms supports OAuth and OpenID. These authentication enhancements allow users to log into your site using existing credentials, from such accounts as Facebook, Twitter, Windows Live, and Google. By default, the template creates a membership database using a default database name on an instance of SQL Server Express LocalDB, the development database server that comes with Visual Studio Express 2013 for Web.
  5. Client Script and Client Frameworks

    You can enhance the server-based features of ASP.NET by including client-script functionality in ASP.NET Web Form pages. You can use client script to provide a richer, more responsive user interface to users. You can also use client script to make asynchronous calls to the Web server while a page is running in the browser.
  6. Routing

    URL routing allows you to configure an application to accept request URLs that do not map to physical files. A request URL is simply the URL a user enters into their browser to find a page on your web site. You use routing to define URLs that are semantically meaningful to users and that can help with search-engine optimization (SEO).
  7. State Management

    ASP.NET Web Forms includes several options that help you preserve data on both a per-page basis and an application-wide basis.
  8. Security

    An important part of developing a more secure application is to understand the threats to it. Microsoft has developed a way to categorize threats: Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege (STRIDE). In ASP.NET Web Forms, you can add extensibility points and configuration options that enable you to customize various security behaviors in ASP.NET Web Forms.
  9. Performance

    Performance can be a key factor in a successful Web site or project. ASP.NET Web Forms allows you to modify performance related to page and server control processing, state management, data access, application configuration and loading, and efficient coding practices.
  10. Internationalization

    ASP.NET Web Forms enables you to create web pages that can obtain content and other data based on the preferred language setting for the browser or based on the user's explicit choice of language. Content and other data is referred to as resources and such data can be stored in resource files or other sources. In an ASP.NET Web Forms page, you configure controls to get their property values from resources. At run time, the resource expressions are replaced by resources from the appropriate localized resource file.
  11. Debugging and Error Handling

    ASP.NET includes features to help you diagnose problems that might arise in your Web Forms application. Debugging and error handling are well supported  within ASP.NET Web Forms so that your applications compile and run effectively.
  12. Deployment and Hosting

    Visual Studio, ASP.NET, Azure, and IIS provide tools that help you with the process of deploying and hosting your Web Forms application

ASP.Net Component Model:

The ASP.Net  component model provides various building blocks of ASP.Net pages. Basically it is an object model, which describes:

  1. Server side counterparts of almost all HTML elements or tags, like <form> and <input>.
  2. Server controls, which help in developing complex user-interface for example the Calendar control or the Gridview control.

ASP.Net is a technology, which works on the .Net framework that contains all web-related functionalities. The .Net framework is made of an object-oriented hierarchy. An ASP.Net web application is made of pages. When a user requests an ASP.Net page, the IIS delegates the processing of the page to the ASP.Net runtime system. The ASP.Net runtime transforms the .aspx page into an instance of a class, which inherits from the base class Page of the .Net framework. Therefore, each ASP.Net page is an object and all its components i.e., the server-side controls are also objects.

Components of .Net Framework

Before going to the next session on Visual Studio.Net, let us look at the various components of the .Net framework 3.5. The following table describes the components of the .Net framework 3.5 and the job they perform:

  1. Common Language Runtime or CLR

    It performs memory management, exception handling, debugging, security checking, thread execution, code execution, code safety, verification and compilation.Those codes which are directly managed by the CLR are called the managed code. When the managed code is compiled, the compiler converts the source code into a CPU independent intermediate language (IL) code. A Just in time compiler (JIT) compiles the IL code into native code, which is CPU specific.
  2. .Net Framework Class Library

    It contains a huge library of reusable types . classes, interfaces, structures and enumerated values, which are collectively called types
  3. Common Language Specification

    It contains the specifications for the .Net supported languages and implementation of language integration.
  4. Common Type System

    It provides guidelines for declaring, using and managing types at runtime, and cross-language communication.
  5. Metadata and Assemblies

    Metadata is the binary information describing the program, which is either stored in a portable executable file (PE) or in the memory. Assembly is a logical unit consisting of the assembly manifest, type metadata, IL code and set of resources like image files etc.
  6. Windows Forms

    This contains the graphical representation of any window displayed in the application.
  7. ASP.Net and ASP.Net AJAX

    ASP.Net is the web development model and AJAX is an extension of ASP.Net for developing and implementing AJAX functionality. ASP.Net AJAX contains the components that allow the developer to update data on a website without a complete reload of the page.
  8. ADO.Net

    It is the technology used for working with data and databases. It provides accesses to data sources like SQL server, OLE DB, XML etc. The ADO .Net allows connection to data sources for retrieving, manipulating and updating data.
  9. (Windows Workflow Foundation (WF)

    It helps in building workflow based applications in Windows. It contains activities, workflow runtime, workflow designer and a rules engine.
  10. Windows Presentation Foundation

    It provides a separation between the user interface and the business logic. It helps in developing visually stunning interfaces using documents, media, two and three dimensional graphics, animations and more.
  11. Windows Communication Foundation (WCF)

    It is the technology used for building and running connected systems
  12. Windows CardSpace

    It provides safety of accessing resources and sharing personal information on the internet.
  13. LINQ

    It imparts data querying capabilities to .Net languages using a syntax which is similar to the tradition query language SQL.

Let Us get Started

It is easy to write ASP.NET pages, in either Notepad.exe, or the newly released Visual Studio.NET. Notepad is free and provides an alternative to Visual Studio. Let’s use Visual studio and write our first valid ASP.NET page. When you create new ASP.NET Web Application (Assume Topic1)in Visual studio , it will automatically create aspx with code behind like shown below:

default.aspx

  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Topic1._default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Hello this is my first server side page
    </div>
    </form>
</body>
</html>

       
default.aspx.cs(code behind)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Topic1
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

Now, just your web application like shown below

You should see the following results in your Internet Explorer browser:

This ASPX page is perfectly valid ASP.NET page.

Deciding When to Create a Web Forms Application

You must consider carefully whether to implement a Web application by using either the ASP.NET Web Forms model or another model, such as the ASP.NET MVC framework. The MVC framework does not replace the Web Forms model; you can use either framework for Web applications. Before you decide to use the Web Forms model or the MVC framework for a specific Web site, weigh the advantages of each approach.

Advantages of a Web Forms-Based Web Application

The Web Forms-based framework offers the following advantages:

  1. It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.
  2. It uses a Page Controller pattern that adds functionality to individual pages. For more information, see Page Controller on the MSDN Web site.
  3. It uses view state or server-based forms, which can make managing state information easier.
  4. It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development.
  5. In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model.

Advantages of an MVC-Based Web Application

The ASP.NET MVC framework offers the following advantages:

  1. It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
  2. It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
  3. It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure. For more information, see Front Controller on the MSDN Web site.
  4. It provides better support for test-driven development (TDD).
  5. It works well for Web applications that are supported by large teams of developers and Web designers who need a high degree of control over the application behavior.

.NET Framework’s Architectural Structure

NET is component- based and contains a large collection of abstract interfaces and classes. They provide the supporting structure for creating reusable components, designed especially for rendering elements on a web form. ASP.NET, the Internet segment, is one of five primary components included in the Framework in addition to the CLR, CTS, CLS, and ADO.NET. One of the innovative features in ASP.NET supports running controls on the server side rather than on the client. This results in improved performance by allowing the developer to control server-side controls programmatically. Additionally, your Microsoft Intermediate Language (MSIL) code is compiled rather than interpreted as was the case with classic ASP pages. This improves performance substantially. The framework supports Web services through namespaces hosting classes such as System.UI.Web Controls. The classes in System.Web.UI are grouped as a hierarchical tree beginning with the Control class. This is the parent class from which all other controls are inherited. They include buttons, text boxes, and drop-down lists. {mospagebreak title=Examining the Code-behind feature} Separating business logic from the presentation layer receives support from the runtime by providing the new code-behind feature. You begin by deriving from the Page class. Then place your code in an .aspx file and insert a reference to another file containing the business logic

ASP.NET Page Life cycle

Here is the page lifecycle processed step-by-step. The figure displayed here illustrates an ASP.NET’s page lifecycle. Each time a request arrives at a Web server for an ASP.NET Web page, the first thing the Web server does is hand off the request to the ASP.NET engine. The ASP.NET engine then takes the request through a pipeline composed of numerous stages, which includes verifying file access rights for the ASP.NET Web page, resurrecting the user's session state, and so on. At the end of the pipeline, a class corresponding to the requested ASP.NET Web page is instantiated and the ProcessRequest() method is invoked (see Figure below). asp.net-page-lifecycle
What is important to realize is that each and every time an ASP.NET Web page is requested it goes through these same life cycle stages (shown in Figure below).
Page Events

  1. The initial event begins with an HTTP URL client request for rendering a specified page to the client’s browser.
  2. The Load event fires next. The CLR uses reflection to examine the .aspx page and determine whether the page is called for the first time, or represents a post back through user interaction with a button or some other page control.
  3. If the event is a first-time request, the code is converted to a class.
  4. The class compiles to an assembly and is stored in a valid Internet Information Server virtual directory where the page’s location can be determined.
  5. If the page is posted back, ASP.NET restores any data residing in hidden fields (ViewState) and passes the information to the server.
  6. The control event triggering the post back fires. At this stage, all control events are initiated. The change events fire first; those events are stored in the browser and execute only when the client sends the page back to the server. After a control event fires, the page is rendered to the browser.
  7. Before Page_Unloadunloads the page from server memory, a final event performs any cleanup tasks before the unload method disposes the page.

Many other features are supported in ASP.NET by the Common Language runtime. They include Web Forms, the new programming model for ASP.Net, Server Controls, Web Services, Caching, and Configuration improvements. In the next article we will focus on the enhanced session-state management model in ASP.NET, as well as taking a look at Page Directives. We’ll meet again in the next article. Happy Explorations in ASP.NET.

ASP.NET

ASP.NET is a new server side technlogy. It is not compatible with Classic ASP, but ASP.NET may include Classic ASP. ASP.NET pages are compiled, which makes them faster than Classic ASP. ASP.NET has better language support, a large set of user controls, XML-based components, and integrated user authentication. ASP.NET pages have the extension .aspx, and are normally written in VB (Visual Basic) or C# (C sharp). User controls in ASP.NET can be written in different languages, including C++ and Java. When a browser requests an ASP.NET file, the ASP.NET engine reads the file, compiles and executes the scripts in the file, and returns the result to the browser as plain HTML.

What is Web Forms?

Web Forms is one of the 3 programming models for creating ASP.NET web sites and web applications. The other two programming models are Web Pages and MVC (Model, View, Controller). Web Forms is the oldest ASP.NET programming model, with event driven web pages written as a combination of HTML, server controls, and server code. Web Forms are compiled and executed on the server, which generates the HTML that displays the web pages. Web Forms comes with hundreds of different web controls and web components to build user-driven web sites with data access.

Visual Studio Express 2012/2010

Visual Studio Express is a free version of Microsoft Visual Studio. Visual Studio Express is a development tool tailor made for Web Forms (and MVC). Visual Studio Express contains:

  1. MVC and Web Forms
  2. Drag-and-drop web controls and web components
  3. A web server language (Razor using VB or C#)
  4. A web server (IIS Express)
  5. A database server (SQL Server Compact)
  6. A full web development framework (ASP.NET)

If you install Visual Studio Express, you will get more benefits from this tutorial. If you want to install Visual Studio Express, click on one of these links: Visual Web Developer 2012 (If you have Windows 7 or Windows 8) Visual Web Developer 2010 (If you have Windows Vista or XP)

ASP.NET - Server Controls

ASP.NET has solved the "spaghetti-code" problem described above with server controls. Server controls are tags that are understood by the server. There are three kinds of server controls:

  1. HTML Server Controls - Traditional HTML tags
  2. Web Server Controls - New ASP.NET tags
  3. Validation Server Controls - For input validation

ASP.NET - HTML Server Controls

HTML server controls are HTML tags understood by the server. HTML elements in ASP.NET files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control. The id attribute is added to identify the server control. The id reference can be used to manipulate the server control at run time. Note: All HTML server controls must be within a <form> tag with the runat="server" attribute. The runat="server" attribute indicates that the form should be processed on the server. It also indicates that the enclosed controls can be accessed by server scripts. In the following example we declare an HtmlAnchor server control in an .aspx file. Then we manipulate the HRef attribute of the HtmlAnchor control in an event handler (an event handler is a subroutine that executes code for a given event). The Page_Load event is one of many events that ASP.NET understands:

<script runat="server">
Sub Page_Load
link1.HRef="http://www.shabirhakim.net"
End Sub
</script>
<html>
<body>
<form runat="server">
<a id="link1" runat="server">Visit shabirhakim.net!</a>
</form>
</body>
</html>

The executable code itself has been moved outside the HTML.

ASP.NET - Web Server Controls

Web server controls are special ASP.NET tags understood by the server. Like HTML server controls, Web server controls are also created on the server and they require a runat="server" attribute to work. However, Web server controls do not necessarily map to any existing HTML elements and they may represent more complex elements. The syntax for creating a Web server control is:

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

In the following example we declare a Button server control in an .aspx file. Then we create an event handler for the Click event which changes the text on the button:

<script runat="server">
Sub submit(Source As Object, e As EventArgs)
button1.Text="You clicked me!"
End Sub
</script>
<html>
<body>
<form runat="server">
<asp:Button id="button1" Text="Click me!"
runat="server" OnClick="submit"/>
</form>
</body>
</html>

ASP.NET - Validation Server Controls

Validation server controls are used to validate user-input. If the user-input does not pass validation, it will display an error message to the user. Each validation control performs a specific type of validation (like validating against a specific value or a range of values). By default, page validation is performed when a Button, ImageButton, or LinkButton control is clicked. You can prevent validation when a button control is clicked by setting the CausesValidation property to false. The syntax for creating a Validation server control is:

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

In the following example we declare one TextBox control, one Button control, and one RangeValidator control in an .aspx file. If validation fails, the text "The value must be from 1 to 100!" will be displayed in the RangeValidator control:

Code Snippet
<html>
<body>
<form runat="server">
<p>Enter a number from 1 to 100:
<asp:TextBox id="tbox1" runat="server" />
<br /><br />
<asp:Button Text="Submit" runat="server" />
</p>
<p>
<asp:RangeValidator
ControlToValidate="tbox1"
MinimumValue="1"
MaximumValue="100"
Type="Integer"
Text="The value must be from 1 to 100!"
runat="server" />
</p>
</form>
</body>
</html>

An Event Handler is a subroutine that executes code for a given event.

ASP.NET - Event Handlers

Look at the following code:


<%
lbl1.Text="The date and time is " & now()
%>

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

When will the code above be executed? The answer is: "You don't know..."

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:

Code Snippet
<script runat="server">
Sub Page_Load
lbl1.Text="The date and time is " & now()
End Sub
</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):

Code Snippet
<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
  lbl1.Text="The date and time is " & now()
end if
End Sub
Sub submit(s As Object, e As EventArgs)
lbl2.Text="As Usual Hello world!"
End Sub
</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>

The example above will write the "The date and time is...." message only the first time the page is loaded. When a user clicks on the Submit button, the submit subroutine will write "As Usual Hello world!" to the second label, but the date and time in the first label will not change. All server controls must appear within a <form> tag, and the <form> tag must contain the runat="server" attribute


ASP.NET Web Forms

All server controls must appear within a <form> tag, and the <form> tag must contain the runat="server" attribute. The runat="server" attribute indicates that the form should be processed on the server. It also indicates that the enclosed controls can be accessed by server scripts:

<form runat="server">
...HTML + server controls
</form>

Note: The form is always submitted to the page itself. If you specify an action attribute, it is ignored. If you omit the method attribute, it will be set to method="post" by default. Also, if you do not specify the name and id attributes, they are automatically assigned by ASP.NET. Note: An .aspx page can only contain ONE <form runat="server"> control! If you select view source in an .aspx page containing a form with no name, method, action, or id attribute specified, you will see that ASP.NET has added these attributes to the form. It looks something like this:

<form name="_ctl0" method="post" action="page.aspx" id="_ctl0">
...some code
</form>

Submitting a Form

A form is most often submitted by clicking on a button. The Button server control in ASP.NET has the following format:

<asp:Button id="id" text="label" OnClick="sub" runat="server" />

defines a unique name for the button and the text attribute assigns a label to the button. The onClick event handler specifies a named subroutine to execute. In the following example we declare a Button control in an .aspx file. A button click runs a subroutine which changes the text on the button: You may save a lot of coding by maintaining the ViewState of the objects in your Web Form.


Maintaining the ViewState

When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState. When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control. The source could look something like this:

<form name="_ctl0" method="post" action="page.aspx" id="_ctl0">
<input type="hidden" name="__VIEWSTATE"
value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />
.....some code
</form>

Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to NOT maintain the ViewState, include the directive<.p>

<%@ Page EnableViewState="false" %> at the top of an .aspx page or add the attribute EnableViewState="false"

to any control. 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:

Code Snippet
<html>
<body>
<form action="demo_classicasp.aspx" method="post">
Your name: <input type="text" name="fname" size="20">
<input type="submit" value="Submit">
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!")
End If
%>
</body>
</html>

Here is the new ASP .NET way. When you click on the submit button, the form value will NOT disappear:

Code Snippet

Click view source in the right frame of the example to see that ASP .NET has added a hidden field in the form to maintain the ViewState

<script runat="server">
Sub submit(sender As Object, e As EventArgs)
lbl1.Text="Hello " & txt1.Text & "!"
End Sub
</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 is used to create a text box where the user can input text.


The TextBox Control

The TextBox control is used to create a text box where the user can input text. The TextBox control's attributes and properties are listed in our web controls reference page. The example below demonstrates some of the attributes you may use with the TextBox control:

Code Snippet
<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="As Usual 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>

Add a Script

The contents and settings of a TextBox control may be changed by server scripts when a form is submitted. A form can be submitted by clicking on a button or when a user changes the value in the TextBox control. In the following example we declare one TextBox control, one Button control, and one Label control in an .aspx file. When the submit button is triggered, the submit subroutine is executed. The submit subroutine writes a text to the Label control:

Code Snippet
<script runat="server">
Sub submit(sender As Object, e As EventArgs)
lbl1.Text="Your name is " & txt1.Text
End Sub
</script>

<html>
<body>

<form runat="server">
Enter 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>

In the following example we declare one TextBox control and one Label control in an .aspx file. When you change the value in the TextBox and either click outside the TextBox or press the Tab key, the change subroutine is executed. The submit subroutine writes a text to the Label control:

Code Snippet
<script runat="server">
Sub change(sender As Object, e As EventArgs)
lbl1.Text="You changed text to " & txt1.Text
End Sub
</script>

<html>
<body>

<form runat="server">
Enter your name:
<asp:TextBox id="txt1" runat="server"
text="As Usual Hello world!"
ontextchanged="change" autopostback="true"/>
<p><asp:Label id="lbl1" runat="server" /></p>
</form>

</body>
</html>

The Button Control

The Button control is used to display a push button. The push button may be a submit button or a command button. By default, this control is a submit button. A submit button does not have a command name and it posts the page back to the server when it is clicked. It is possible to write an event handler to control the actions performed when the submit button is clicked. A command button has a command name and allows you to create multiple Button controls on a page. It is possible to write an event handler to control the actions performed when the command button is clicked. The Button control's attributes and properties are listed in our web controls reference page. The example below demonstrates a simple Button control:


<html>
<body>

<form runat="server">
<asp:Button id="b1" Text="Submit" runat="server" />
</form>

</body>
</html>

Add a Script

A form is most often submitted by clicking on a button. In the following example we declare one TextBox control, one Button control, and one Label control in an .aspx file. When the submit button is triggered, the submit subroutine is executed. The submit subroutine writes a text to the Label control:

Code Snippet
<script runat="server">
Sub submit(sender As Object, e As EventArgs)
lbl1.Text="Your name is " & txt1.Text
End Sub
</script>

<html>
<body>

<form runat="server">
Enter 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>

We may use data binding to fill lists with selectable items from an imported data source, like a database, an XML file, or a script.


Data Binding

The following controls are list controls which support data binding:

  1. asp:RadioButtonList
  2. asp:CheckBoxList
  3. asp:DropDownList
  4. 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>

However, with data binding we may use a separate source, like a database, an XML file, or a script to fill the list with selectable items. By using an imported source, the data is separated from the HTML, and any changes to the items are made in the separate data source. In the next three chapters, we will describe how to bind data from a scripted data source. The ArrayList object is a collection of items containing a single data value.


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">
Sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New ArrayList
  mycountries.Add("Norway")
  mycountries.Add("Sweden")
  mycountries.Add("France")
  mycountries.Add("Italy")
end if
end sub
</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:

  1. asp:RadioButtonList
  2. asp:CheckBoxList
  3. asp:DropDownList
  4. 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:

Code Snippet
<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()
  rb.DataSource=mycountries
  rb.DataBind()
end if
end sub
</script>

<html>
<body>

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

</body>
</html>

The DataSource property of the RadioButtonList control is set to the ArrayList and it defines the data source of the RadioButtonList control. The DataBind() method of the RadioButtonList control binds the data source with the RadioButtonList control. Note: The data values are used as both the Text and Value properties for the control. To add Values that are different from the Text, use either the Hashtable object or the SortedList object. The Hashtable object contains items in key/value pairs.

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">
Sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New Hashtable
  mycountries.Add("N","Norway")
  mycountries.Add("S","Sweden")
  mycountries.Add("F","France")
  mycountries.Add("I","Italy")
end if
end sub
</script>

Data Binding

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

  1. asp:RadioButtonList
  2. asp:CheckBoxList
  3. asp:DropDownList
  4. 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">
sub Page_Load
if Not Page.IsPostBack then
  dim 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()
end if
end sub
</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:

Code Snippet
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim 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()
end if
end sub

sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
end sub
</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>

Note: You cannot choose the sort order of the items added to the Hashtable. To sort items alphabetically or numerically, use the SortedList object. The SortedList object combines the features of both the ArrayList object and the Hashtable object.

The SortedList Object

The SortedList object contains items in key/value pairs. A SortedList object automatically sorts the items in alphabetic or numeric order. Items are added to the SortedList with the Add() method. A SortedList can be sized to its final size with the TrimToSize() method. The following code creates a SortedList named mycountries and four elements are added:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New SortedList
  mycountries.Add("N","Norway")
  mycountries.Add("S","Sweden")
  mycountries.Add("F","France")
  mycountries.Add("I","Italy")
end if
end sub
</script>

Data Binding

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

  1. asp:RadioButtonList
  2. asp:CheckBoxList
  3. asp:DropDownList
  4. 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">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New SortedList
  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()
end if
end sub
</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:

Code Snippet
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New SortedList
  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()
end if
end sub

sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
end sub
</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>

Bind a DataSet to a List Control

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" %>

Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is first loaded:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New DataSet
  mycountries.ReadXml(MapPath("countries.xml"))
end if
end sub

To bind the DataSet 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 XML DataSet:

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

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New DataSet
  mycountries.ReadXml(MapPath("countries.xml"))
  rb.DataSource=mycountries
  rb.DataValueField="value"
  rb.DataTextField="text"
  rb.DataBind()
end if
end sub
</script>

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
</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:

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

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New DataSet
  mycountries.ReadXml(MapPath("countries.xml"))
  rb.DataSource=mycountries
  rb.DataValueField="value"
  rb.DataTextField="text"
  rb.DataBind()
end if
end sub

sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
end sub
</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>

The Repeater control is used to display a repeated list of items that are bound to the control


Bind a DataSet to a Repeater Control

The Repeater control is used to display a repeated list of items that are bound to the control. The Repeater control may be bound to a database table, an XML file, or another list of items. Here we will show how to bind an XML file 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" %>

Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is first loaded:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycdcatalog=New DataSet
  mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
end if
end sub

Then we create a Repeater control in an .aspx page. The contents of the <HeaderTemplate> element are rendered first and only once within the output, then the contents of the <ItemTemplate> element are repeated for each "record" in the DataSet, and last, the contents of the <FooterTemplate> element are rendered once within the output:

<html>
<body>

<form runat="server">
<asp:Repeater id="cdcatalog" runat="server">

<HeaderTemplate>
...
</HeaderTemplate>

<ItemTemplate>
...
</ItemTemplate>

<FooterTemplate>
...
</FooterTemplate>

</asp:Repeater>
</form>

</body>
</html>

Then we add the script that creates the DataSet and binds the mycdcatalog DataSet to the Repeater control. We also fill the Repeater control with HTML tags and bind the data items to the cells in the<ItemTemplate> section with the <%#Container.DataItem("fieldname")%> method:

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

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycdcatalog=New DataSet
  mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
  cdcatalog.DataSource=mycdcatalog
  cdcatalog.DataBind()
end if
end sub
</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:

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

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycdcatalog=New DataSet
  mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
  cdcatalog.DataSource=mycdcatalog
  cdcatalog.DataBind()
end if
end sub
</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:

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

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycdcatalog=New DataSet
  mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
  cdcatalog.DataSource=mycdcatalog
  cdcatalog.DataBind()
end if
end sub
</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 is, like the Repeater control, used to display a repeated list of items that are bound to the control. However, the DataList control adds a table around the data items by default.


Bind a DataSet to a DataList Control

The DataList control is, like the Repeater control, used to display a repeated list of items that are bound to the control. However, the DataList control adds a table around the data items by default. The DataList control may be bound to a database table, an XML file, or another list of items. Here we will show how to bind an XML file to a DataList 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" %>

Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is first loaded:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycdcatalog=New DataSet
  mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
end if
end sub

Then we create a DataList in an .aspx page. The contents of the <HeaderTemplate> element are rendered first and only once within the output, then the contents of the <ItemTemplate> element are repeated for each "record" in the DataSet, and last, the contents of the <FooterTemplate> element are rendered once within the output:

<html>
<body>

<form runat="server">
<asp:DataList id="cdcatalog" runat="server">

<HeaderTemplate>
...
</HeaderTemplate>

<ItemTemplate>
...
</ItemTemplate>

<FooterTemplate>
...
</FooterTemplate>

</asp:DataList>
</form>

</body>
</html>

Then we add the script that creates the DataSet and binds the mycdcatalog DataSet to the DataList control. We also fill the DataList control with a <HeaderTemplate> that contains the header of the table, an <ItemTemplate> that contains the data items to display, and a <FooterTemplate> that contains a text. Note that the gridlines attribute of the DataList is set to "both" to display table borders:

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

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycdcatalog=New DataSet
  mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
  cdcatalog.DataSource=mycdcatalog
  cdcatalog.DataBind()
end if
end sub
</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:

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

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycdcatalog=New DataSet
  mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
  cdcatalog.DataSource=mycdcatalog
  cdcatalog.DataBind()
end if
end sub
</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>

Using the <AlternatingItemTemplate>

You can add an <AlternatingItemTemplate> element after the <ItemTemplate> element to describe the appearance of alternating rows of output. You may style the data in the <AlternatingItemTemplate> section within the DataList control:

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

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycdcatalog=New DataSet
mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
cdcatalog.DataSource=mycdcatalog
cdcatalog.DataBind()
end if
end sub
</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"
alternatingitemstyle-backcolor="#e8e8e8"
alternatingitemstyle-forecolor="#000000"
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>

<AlternatingItemTemplate>
"<%#Container.DataItem("title")%>" of
<%#Container.DataItem("artist")%> -
$<%#Container.DataItem("price")%>
</AlternatingItemTemplate>

<FooterTemplate>
&copy; Hege Refsnes
</FooterTemplate>

</asp:DataList>
</form>

</body>
</html>

What is ADO.NET?

  1. ADO.NET is a part of the .NET Framework
  2. ADO.NET consists of a set of classes used to handle data access
  3. ADO.NET is entirely based on XML
  4. ADO.NET has, unlike ADO, no Recordset object

Create a Database Connection

We are going to use the simple user database in our examples. First, import the "using System.Data.SqlClient;" 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:

using System.Data.SqlClient;

 protected void Page_Load(object sender, EventArgs e)
    {
  ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings["strSqlConnection"];

            if (mySetting == null || string.IsNullOrEmpty(mySetting.ConnectionString))
                throw new Exception("Fatal error: missing connecting string in web.config file");
            string connString = mySetting.ConnectionString;
    SqlConnection con = new SqlConnection(connString)
    con.Open()
}
 
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 SqlCommand class. The SqlCommand class is for issuing SQL queries against database tables:


   protected void Page_Load(object sender, EventArgs e)
        {

 using (SqlConnection con = new SqlConnection(connString))
            {
                con.Open();
                // create a command to check if the device exists
                using (SqlCommand cmd = new SqlCommand("select count(*) from User_Master where UserEmailAddress = @UserEmailAddress", con))
                {
                    cmd.Parameters.AddWithValue("UserEmailAddress", userEmail);
                  
                }  
            }
}
 

Create a DataReader

The SqlDataReader class is used to read a stream of records from a data source. A DataReader is created by calling the ExecuteReader method of the SqlCommand object:

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

  protected void Page_Load(object sender, EventArgs e)
        {
  ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings["strSqlConnection"];

            if (mySetting == null || string.IsNullOrEmpty(mySetting.ConnectionString))
                throw new Exception("Fatal error: missing connecting string in web.config file");
            string connString = mySetting.ConnectionString;
            bool exists;

            using (SqlConnection con = new SqlConnection(connString))
            {
                con.Open();
                // create a command to check if the device exists
                using (SqlCommand cmd = new SqlCommand("select count(*) from User_Master where UserEmailAddress = @UserEmailAddress", con))
                {
                    cmd.Parameters.AddWithValue("UserEmailAddress", userEmail);
                   //Creating Reader
                    exists = (int)cmd.ExecuteScalar() > 0;
                }

                // if exists, return a message error
                if (exists)
                {

                    return true;
                }
                else
                {
                    loginmsg.Text = "User doesn't exist in our catalog";
                    return false;
                }


            }
}

Bind to a Repeater Control

Then we bind the DataReader to a Repeater control:

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

<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
data source=" & server.mappath("northwind.mdb"))
dbconn.Open()
sql="SELECT * FROM Users"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
Users.DataSource=dbread
Users.DataBind()
dbread.Close()
dbconn.Close()
end sub
</script>

<html>
<body>

<form runat="server">
<asp:Repeater id="Users" runat="server">

<HeaderTemplate>
<table border="1" width="100%">
<tr>
<th>PersonName</th>
<th>Contactname</th>
<th>Address</th>
<th>City</th>
</tr>
</HeaderTemplate>

<ItemTemplate>
<tr>
<td><%#Container.DataItem("PersonName")%></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 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 contain 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.


Master Page Example


<%@ Master %>

<html>
<body>
<h1>Standard Header From Masterpage</h1>
<asp:ContentPlaceHolder id="CPH1" runat="server">
</asp:ContentPlaceHolder>
</body>
</html>

The master page above is a normal HTML page designed as a template for other pages. The @ Master directive defines it as a master page. The master page contains a placeholder tag <asp:ContentPlaceHolder> for individual content. The id="CPH1" attribute identifies the placeholder, allowing many placeholders in the same master page. This master page was saved with the name "master1.master".

Note Note: The master page can also contain code, allowing dynamic content.

Content Page Example

<%@ Page MasterPageFile="master1.master" %>

<asp:Content ContentPlaceHolderId="CPH1" runat="server">
  <h2>Individual Content</h2>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</asp:Content>

The content page above is one of the individual content pages of the web. The @ Page directive defines it as a standard content page. The content page contains a content tag <asp:Content> with a reference to the master page (ContentPlaceHolderId="CPH1"). This content page was saved with the name "mypage1.aspx". When the user requests this page, ASP.NET merges the content page with the master page.

Click to display mypage1.aspx.
Note Note: The content text must be inside the <asp:Content> tag. No content is allowed outside the tag.

Content Page With Controls


<%@ Page MasterPageFile="master1.master" %>

<asp:Content ContentPlaceHolderId="CPH1" runat="server">
  <h2>shabirhakim.net</h2>
  <form runat="server">
    <asp:TextBox id="textbox1" runat="server" />
    <asp:Button id="button1" runat="server" text="Button" />
  </form>
</asp:Content>

The content page above demonstrates how .NET controls can be inserted into the content page just like an into an ordinary page.

Web Site Navigation

Maintaining the menu of a large web site is difficult and time consuming. In ASP.NET the menu can be stored in a file to make it easier to maintain. This file is normally called web.sitemap, and is stored in the root directory of the web. In addition, ASP.NET has three new navigation controls:

  1. Dynamic menus
  2. TreeViews
  3. Site Map Path

The Sitemap File

The following sitemap file is used in this tutorial:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<siteMap>
  <siteMapNode title="Home" url="/aspnet/shabirhakim/home.aspx">
    <siteMapNode title="Services" url="/aspnet/shabirhakim/services.aspx">
      <siteMapNode title="Training" url="/aspnet/shabirhakim/training.aspx"/>
      <siteMapNode title="Support" url="/aspnet/shabirhakim/support.aspx"/>
    </siteMapNode>
  </siteMapNode>
</siteMap>

Rules for creating a sitemap file:

  1. The XML file must contain a <siteMap> tag surrounding the content
  2. The <siteMap> tag can only have one <siteMapNode> child node (the "home" page)
  3. Each <siteMapNode> can have several child nodes (web pages)
  4. Each <siteMapNode> has attributes defining page title and URL
Note Note: The sitemap file must be placed in the root directory of the web and the URL attributes must be relative to the root directory.

Dynamic Menu

The <asp:Menu> control displays a standard site navigation menu.


Code Syntax:
<asp:SiteMapDataSource id="nav1" runat="server" />

<form runat="server">
<asp:Menu runat="server" DataSourceId="nav1" />
</form>

The <asp:Menu> control in the example above is a placeholder for a server created navigation menu. The data source of the control is defined by the DataSourceId attribute. The id="nav1" connects it to the  <asp:SiteMapDataSource> control. The <asp:SiteMapDataSource> control automatically connects to the default sitemap file (web.sitemap).


TreeView

The <asp:TreeView> control displays a multi level navigation menu. The menu looks like a tree with branches that can be opened or closed with + or - symbol.


Code Syntax:
<asp:SiteMapDataSource id="nav1" runat="server" />

<form runat="server">
<asp:TreeView runat="server" DataSourceId="nav1" />
</form>

The <asp:TreeView> control in the example above is a placeholder for a server created navigation menu. The data source of the control is defined by the DataSourceId attribute. The id="nav1" connects it to the  <asp:SiteMapDataSource> control. The <asp:SiteMapDataSource> control automatically connects to the default sitemap file (web.sitemap).


SiteMapPath

The SiteMapPath control displays the trail (navigation path) to the current page. The path acts as clickable links to previous pages. Unlike the TreeView and Menu control the SiteMapPath control does NOT use a SiteMapDataSource. The SiteMapPath control uses the web.sitemap file by default.

Note

Tips: If the SiteMapPath displays incorrectly, most likely there is a URL error (typo) in the web.sitemap file.


Code Syntax:
<form runat="server">
<asp:SiteMapPath runat="server" />
</form>

The <asp:SiteMapPath> control in the example above is a placeholder for a server created site path display.


How DataReader Works and How is it different from Dataset ?

About Data set and Data Reader


Introduction

ADO.NET offers two data classes for query results: the DataReader and the DataSet.
Determining which is best for your application involves careful analysis. Consider these factors before making a decision. If you use the SqlDataReader, note the following:


  1. The underlying connection to the database remains open and cannot be used for any other purpose while the data reader is active. Call Close on the SqlDataReader as soon as possible.
  2. There can be only one data reader per connection.
  3. You can close the connection explicitly when you finish with the data reader, or tie the lifetime of the connection to the SqlDataReader object, by passing the CommandBehavior.CloseConnection enumerated value to the ExecuteReader method. This indicates that the connection should be closed when the SqlDataReader is closed.
  4. When accessing data by using the reader, use the typed accessor methods (such as GetInt32 and GetString) if you know the column's underlying data type because they reduce the amount of type conversion required when you read column data.
  5. To avoid unnecessary data being pulled from server to client, if you want to close the reader and discard any remaining results, call the command object's Cancel method before calling Close on the reader. Cancel ensures that the results are discarded on the server and are not pulled unnecessarily to the client. Conversely, calling Close on the data reader causes the reader to unnecessarily pull the remaining results to empty the data stream.
  6. If you want to obtain output or return values returned from a stored procedure and you are using the ExecuteReader method of the SqlCommand object, you must call the Close method on the reader before the output and return values are available.

What is a DataReader?

DataReaders are different–they provide forward-only, read-only, connected access to data sources, and they don't support data manipulation. So why would you want to use something that limits you so much? Performance, for starters: DataReaders are much faster. Another benefit is a smaller memory footprint–DataReaders allow you to work with data as you get it, a row at a time. So DataReaders are particularly well-suited for working with data that's too large to fit in memory comfortably. A DataReader is a read-only stream of data returned from the database as the query executes. It only contains one row of data in memory at a time and is restricted to navigating forward only in the results one record at a time. The DataReader does support access to multiple result sets, but only one at a time and in the order retrieved. Just as in the original version of ADO, the data is no longer available through the DataReader once the connection to the data source is closed, which means a DataReader requires a connection to the database throughout its usage. Output parameters or return values are only available through the DataReader once the connection is closed.

DataReaders all implement the same IDataReader interface, which means that all of the DataReaders should provide the same set of functionality. Each DataReader implementation is optimized for a specific data provider such as SQL Server or Oracle. Version 1.0 of the Microsoft .NET Framework includes a System.Data.SqlClient.SqlDataReader that is specific to SQL Server and a System.Data.OleDb.OleDbDataReader that is more generic for OLEDB providers. Version 1.1 of the .NET Framework introduced the SqlCeDataReader for connecting to the SQL Server edition for Windows CE, OdbcDataReader for ODBC data sources, and OracleDataReader for connecting to Oracle databases. It isn''t required that you use the DataReaders from Microsoft, and each database vendor often has its own .NET provider. In addition, you can implement a DataReader of your own through the IDataReader interface.


Retrieving a Single Item

In this scenario, you want to retrieve a single item of data. For example, you might want to look up a single product name, given its ID, or a single customer credit rating, given the customer's name. In such scenarios, you will generally not want to incur the overhead of a DataSet or even a DataTable when retrieving a single item. You might also want simply to check whether a particular row exists in the database. For example, as a new user registers on a Web site, you need to check whether or not the chosen user name already exists. This is a special case of the single item lookup, but in this case, a simple Boolean return is sufficient.


Comparing the Options

Consider the following options when you retrieve a single item of data from a data source:


  1. Use the ExecuteScalar method of a SqlCommand object with a stored procedure.
  2. Use a stored procedure output or return parameter.
  3. Use a SqlDataReader object.

The ExecuteScalar method returns the data item directly because it is designed for queries that only return a single value. It requires less code than either the stored procedure output parameter or SqlDataReader approaches require.. From a performance perspective, you should use a stored procedure output or return parameter because tests have shown that the stored procedure approach offers consistent performance across low and high-stress conditions (from fewer than 100 simultaneous browser connections to 200 browser connections).


Sample DataReader C# code


Ex. object val = Command.ExecuteScalar();
Then check if != null.
ExecuteXmlReader -
Executes the SQL query against SQL Server only,while returning an XmlReader object. 
Prepare - Equivalent to ADO's Command.Prepared = True property.
Useful in caching the SQL command so it runs faster when called more than once.
Ex. Command.Prepare();


Dispose - Releases the resources on the Command object. Used to force garbage collecting, ensuring no resources are being held after our connection is used. Incidentally, by using the Dispose method you automatically call the Connection object's Close method as well.


c#

CSharp Source Code
SqlCommand objCmd = new SqlCommand(Sql , objConnect);
SqlDataReader ObjDr =objCmd.ExecuteReader();
while (ObjDr.Read() == true)
{
Response.Write (objDataReader[0].ToString() + "");
}
// closing Reader object:
objDataReader.Close();
objDataReader = null; objCommand.Dispose();
objCommand = null; objConnect.Close();
objConnect= null; 

Vb.net

Vb.net Source Code
Dim objCmd As New SqlCommand(Sql, ObjConn)
Dim ObjDr As Data.SqlClient.SqlDataReader = objCmd.ExecuteReader()
while ObjDr.Read() = True
Response.Write(ObjDr(0).ToString() & "")
End while ' closing
    Reader object:
ObjDr.Close()
ObjDr = Nothing

objCmd.Dispose()
objCmd = Nothing
ObjConn.Close()
ObjConn = Nothing

When not to use Sql Data Reader ?

Don’t use Sql Data Reader when you don’t need to unecessarily keep a database connection open. It’s more efficient to use a disconnected data source model, meaning that you fetch all the data that is required at the beginning, and then close the connection. This is already implemented for you in SqlHelper.ExecuteDataSet().. If you are doing a big loop and outside the loop it has while (dr.read()) you will start to use up all your database connections pretty fast if your site gets moderately busy. In most cases you won’t need this, so just use ExecuteDataSet instead. If you do need to grab the data as you are going along and use it, for example when your data source is very large, or when you want to do asynchronous work on the data, then its a good idea to use SqlDataReader so you can process the data as it comes (rather than waiting until the entire data results are available) As well, DON’T FORGET, you need to explicitly close your Database connections, best to have a try { } catch { } and in the finally { } block you can put conn.Close(), otherwise if there is an exception you will have a connection that is going to stay open until .NET decides to dispose of it


How do I know which one to use?


You can use the following information to help you decide which data retrieval is right for your purposes.



When to consider using a DataReader:



  1. The DataReader is a better choice for applications that require optimised read-only and forward-only access to data such as binding to a DataGrid control. The sooner the data is off-loaded from the DataReader and the connection is closed the better the application performance.
  2. The DataReader is a better choice when you are planning to make repeated calls to retrieve small amounts of information or the data you are retrieving must be as up to date as possible each time it is used.

This is my first article focusing on working with DataReader, stored procedures in ADO.NET. In this article we mainly focus on retrieving values from stored procedures, retrieving by using "ExecuteReader," and retrieving an entire row from a stored procedure. To work with below given example. you need the simple extra tables "UserLogin_Tbl" with database name of your Choice. Let the structures of this table be like shown below


FieldName Datatype
User_ID varchar (30)
User_Password varchar (30)

Retrieving Data, that we can display or process the data in some other way, we have two basic choices. We can use a DataSet object or a DataReader object.
The DataReader approach is generally quicker because it avoids the overhead that is associated with creating a DataSet object. The overhead that is associated with a DataSet object includes creating DataSet subobjects such as DataTables, DataRows, and DataColumns. However, the DataReader provides less flexibility, and is less suited to situations where you have to cache data and pass the data to components in an application that has multiple tiers or we can say if data modification is required, DataReader is not the choice. So DataReader is best choice when we have to display data.
Note The DataAdapter used to fill the DataSet uses a DataReader internally. Use a DataReader when the following conditions are true:
Now Question arises what made me to explain DataReader Again when it is simple object of ADO.NET as other. I agree it is .But fact is that when it comes to using DataReader or returning DataReader, it is bit tricky, where most of the developers get caught. I have seen most of the developers have raised Issue’s regarding returning DataReader from class doesn’t work. Let me make it simple and explain it in simple steps.
Example of  Login Control where we need to fetch username, password to compare it with existing record. I shall look into the same concept, but with any data type and without using RETURN anymore.  Before going to the ADO.NET code, we need to create a simple stored procedure in SQL Server which returns some value.  Using "Query Analyzer," execute the following script
[Note: Don’t forget to create Table [UserLogin_Tbl] within database]



Important Point: Use of Datareader is worth when we just need to Retrieve and display the data.

1. Create Stored procedure "proc_ValidateUser"

CREATEPROCEDURE proc_ValidateUser(@UserID int@User_Password varchar(50) 
                        AS SELECT User_ID, User_Password FROM
UserLogin_Tbl WHERE User_ID = @ User_ID AND User_Password=@User_Password RETURN

The above stored procedure simply uses a SELECT statement to retrieve User_ID and User_Password from UserLogin_Tbl based on the "USERID" and "USERPASSWORD" we send through the parameter "@User_ID & @User_Password."  The stored procedure is named "proc_ValidateUser."  Now, we need to go to ADO.NET to access the same in ASP.NET.

2. Create Class "ClsLogin"

c#

CSharp Source Code


using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
//Author:Shabir
//Dated: 23/01/2009
 public class 
ClsLogin
{
//Your SQL Connection string which is already in the webconfig
 private string DBConstr = ConfigurationManager.ConnectionStrings["FAITHConnStr"].ConnectionString;
 public string homepageURL= "HomePage.aspx";
public string LoginpageURL="Login.aspx";
public ClsLogin()
 { }
 public string getConnectionString
 {
  get
 {
 return DBConstr; 
    
 }
}
public boolLogin(string DBConstr,string Userid, string password)
 {
 try 
 {
SqlConnection objConn= new SqlConnection(getConnectionString);
SqlCommand objcmd=new SqlCommand("proc_ValidateUser", objConn);
objcmd.CommandType=CommandType.StoredProcedure;
/// open  connection
objConn.Open();
objcmd.Parameters.AddWithValue("@User_ID",UserName);
objcmd.Parameters.AddWithValue("@User_Password", password);
 SqlDataReader  ObjDr= objcmd.ExecuteReader(); 
 while (ObjDr.Read())
 {
 if (ObjDr[0].ToString() == Userid 
        &&  ObjDr[1].ToString() == password)
{                   
    HttpContext.Current.Response.Redirect(homepageURL);
}
  }        
 // Close the reader and the connection.  
ObjDr.Close();
return true;
 }
 catch (Exception ex)
  {
 //if exception was raised then redirect to
    loginpage where he has to relogin
// HttpContext.Current.Response.Redirect("Login.aspx?error="+ex.Message);
   }
   finally
   { objConn.Close();}
 }
}

vb.net

vb.net Source Code
                          Imports System
Imports System.Data 
Imports System.Data.SqlClient
Imports System.Web
'Author:Shabir 
'Dated: 23/01/2009 
Public Class ClsLogin
 'Your SQL Connection string which is already in the webconfig
Private DBConstr  As  String
  = ConfigurationManager.ConnectionStrings("FAITHConnStr").ConnectionString  
    Public homepageURL As String ="HomePage.aspx"     
    Public LoginpageURL As String   = "Login.aspx"
    Public Sub  New()
    End Sub
   Public ReadOnly  Property getConnectionString()    As String       Get
    Return DBConstr
   End Get
   End Property
   Public Function  Login(ByVal DBConstr  As String,  ByVal Userid As String, ByVal password  As  String) As Boolean
   Try
   Dim objConn As   New 
        SqlConnection(getConnectionString)
   Dim objcmd As  New 
        SqlCommand("proc_ValidateUser", objConn)             
   objcmd.CommandType = CommandType.StoredProcedure             
    ' open connection.         
   objConn.Open()
   objcmd.Parameters.AddWithValue("@User_ID", UserName)            
    objcmd.Parameters.AddWithValue("@User_Password", password)        Dim ObjDr As 
        SqlDataReader = objcmd.ExecuteReader()
   While ObjDr.Read()
      If ObjDr(0).ToString()  = Userid AndAlso ObjDr(1).ToString() = password Then
          HttpContext.Current.Response.Redirect(homepageURL)           
     End  If 
   End  While          
    ' Close the reader and the connection.           
    ObjDr.Close()           
    Return 
        True
   Catch ex As
        Exception             
    'if exception was raised then redirect to loginpage where he has
        to relogin             
  //  HttpContext.Current.Response.Redirect("Login.aspx?error=" & ex.Message)    
        Finally
   objConn.Close()
   End Try
End Function 
End Class

3 Call Login Method Login on Login Button Click

protected void btnlogin_Click(object sender,EventArgs e){
ClsLogin objlogin=new ClsLogin();
Objlogin.Login(StrConn, txtUsername.Text, txtPassword.Text);}  

Protected sub btnlogin_Click(object sender,EventArgs e)
  Dim  objlogin as new ClsLogin()
    Objlogin.Login(StrConn, txtUsername.Text, txtPassword.Text)    
End sub  

Web Configuration connection section will look like shown below:-

 <connectionStrings>
   <add name="FAITHConnStr" connectionString="Data Source=servername;Initial 
   Catalog=databasename;User ID=sh33abid454y3;Pwd=Sh333w32323abir@123" 
   providerName="System.Data.SqlClient"/>
 </connectionStrings>

                         

Important thing to notice is that while calling Login Method ,I am passing Class Defined Connection as parameter,if new Connection will be opened and tried to login,you will receive Error ExecuteReader requires an open and available Connection. The connection's current state is closed.. As shown in code , "ExecuteReader" is a method which returns a "DataReader" object to pull the information from the database (in this case it is stored procedure) continuously, in a forward only and read-only manner. In the next article, we shall work with DataReader in Deep, Next we will understand data tables, data sets, and so forth using stored procedures. If possible, we shall also look into stored functions and compare both.

Now let me take a simple  example where we will retrieve some fields of the table by using datareader Object.
The DataReadThe DataReader provides the fastest but least flexible way to retrieve data from the database. Data is returned as a read-only, forward-only stream of data that is returned one record at a time. If you need to retrieve many records rapidly, using a DataReader would require less memory than a DataSet, which would need to create a large table to hold the results. The following code example, which requires the User table (see below) , shows how to execute a simple query on SQL database and read the results using a DataReader:


// Create a SQL command  
 string strSQL    = "SELECT UserID,User_FName,User_LName FROM User_Tbl";
 SqlConnection  objConn = new SqlConnection(getConnectionString);
 SqlCommand objcmd = new SqlCommand(strSQL , objConn);
 objcmd.CommandType =CommandType.Text;
//open  connection.   
objConn.Open();
SqlDataReader  ObjDr;
ObjDr = ObjCmd.ExecuteReader(); 
while (ObjDr.Read())
{ 
Console.WriteLine(ObjDr["UserID"].ToString());
Console.WriteLine(ObjDr["User_FName"].ToString()); 
Console.WriteLine(ObjDr["User_LName"].ToString()); 
}
 ObjDr.Close();
// Close the connection 
objConn.Close();

Retrieving a Scalar Value

You can use the ExecuteScalar method of the Command object to return a single value, such as a sum or a count, from the database. The ExecuteScalar method returns the value of the first column of the first row of the result set. The following code example, which requires the User table (see below) ,shows how to retrieve the count of a specified group


// Retrievethe number of Users who whose  age is more than 24
// from the user table // Open connection
string  strSQL = "select count(sal) FROM User_Tbl where age >'24' ; 
SqlConnection objConn = new SqlConnection(getConnectionString);
SqlCommand objcmd = new SqlCommand(strSQL,  objConn); 
objcmd.CommandType = CommandType.Text;             
objConn.Open();
try          
{ 
int count = (int)objcmd.ExecuteScalar();
}   
catch (Exception ex) { 
// Display any exceptions in a messagebox            
MessageBox.Show (ex.Message); 
} // 
 Close the connection   
objConn.Close();

Retrieving Large Data (ADO.NET)


By default, the DataReader loads incoming data as a row as soon as an entire row of data is available. Binary large objects (BLOBs) need different treatment, however, because they can contain gigabytes of data that cannot be contained in a single row. The Command.ExecuteReader method has an overload that will take a CommandBehavior argument to modify the default behavior of the DataReader. You can pass SequentialAccess  to the ExecuteReader method to modify the default behavior of the DataReader so that instead of loading rows of data, it will load data sequentially as it is received.
This is ideal for loading BLOBs or other large data structures. Note that this behavior may depend on your data source. For example, returning a BLOB from Microsoft Access will load the entire BLOB being loaded into memory, rather than sequentially as it is received. When setting the DataReader to use SequentialAccess, it is important to note the sequence in which you access the fields returned. The default behavior of the DataReader, which loads an entire row as soon as it is available, allows you to access the fields returned in any order until the next row is read. When using SequentialAccess however, you must access the fields returned by the DataReader in order. For example, if your query returns three columns, the third of which is a BLOB, you must return the values of the first and second fields before accessing the BLOB data in the third field. If you access the third field before the first or second fields, the first and second field values are no longer available. This is because SequentialAccess has modified the DataReader to return data in sequence and the data is not available after the DataReader has read past it. When accessing the data in the BLOB field, use the GetBytes or GetChars typed accessors of the DataReader, which fill an array with data.
You can also use GetString for character data; however. to conserve system resources you might not want to load an entire BLOB value into a single string variable. You can instead specify a specific buffer size of data to be returned, and a starting location for the first byte or character to be read from the returned data. GetBytes and GetChars will return a long value, which represents the number of bytes or characters returned. If you pass a null array to GetBytes or GetChars, the long value returned will be the total number of bytes or characters in the BLOB.
You can optionally specify an index in the array as a starting position for the data being read.


Example

The following example returns the User ID and photo from the Users Table The User ID (userID) is a character field, and the photo  is an image, which is a BLOB. Because the photo field is a bitmap, the example returns binary data using GetBytes. Notice that the user ID is accessed for the current row of data before the photo, because the fields must be accessed sequentially. Assumes that connection is a valid SqlConnection object from above defined class.

 
 SqlCommand ObjCmd = new SqlCommand("SELECT User_id, User_Photo  FROM User_Tbl",ObjConn);
 // Writes the BLOB to a file (*.bmp).
  FileStream stream;      
 // Streams the BLOB to the FileStream object.  
     BinaryWriter writer;       
// Size of the BLOB buffer.
int bufferSize = 100;  
 // The BLOB byte[] buffer to be filled by GetBytes.
 byte[] outByte = new byte[bufferSize];  
 // The bytes returned from GetBytes.
  long retval; 
// The starting position in the BLOB output.
 long startIndex = 0;     
 // The User ID  to use in the file name.
 string UserID= "";
 // Open the connection and read data into the DataReader.
 ObjConn.Open();
 SqlDataReader ObjRd = ObjCmd.ExecuteReader(CommandBehavior.SequentialAccess);
 while (ObjDr.Read()) { // Get the
 //publisher id, which must occur before getting the logo.
 UserID =ObjDr.GetString(0);
// Create a file to hold the output.
 stream = new FileStream("Photo" + UserID +".bmp",FileMode.OpenOrCreate, FileAccess.Write);     
 writer = new BinaryWriter(stream); 
 startIndex = 0;
retval = ObjDr.GetBytes(1, startIndex, outByte, 0, bufferSize);
 while (retval == bufferSize)
 {
 writer.Write(outByte);
 writer.Flush();
 // Reposition start index to end of last buffer and fill buffer.
 startIndex += bufferSize;
 retval = reader.GetBytes(1,startIndex, outByte, 0, bufferSize);
 } // Write the remaining buffer. 
     
 writer.Write(outByte, 0, (int)retval- 1); 
 writer.Flush(); writer.Close();
     stream.Close(); } 
 ObjDr.Close();
 ObjConn.Close(); 

' Assumes that connection is a valid SqlConnection object from above defined class.

    Dim ObjCmd As  New SqlCommand("SELECT User_id, User_Photo FROM User_Tbl", ObjConn)        
  ' Writes the BLOB to a file (*.bmp).FileStream stream;
  ' Streams the BLOB to the FileStream object.BinaryWriter writer;
  outByte = New Byte(bufferSize - 1) {} 
  ' Open the connection and read data into the DataReader.
   ObjConn.Open()           
    Dim ObjRd As SqlDataReader = ObjCmd.ExecuteReader(CommandBehavior.SequentialAccess)
     While ObjDr.Read()
     'Get the USER id, which must occur before getting   the logo. 
     UserID = ObjDr.GetString(0)  
       ' Create a file to hold the output.          

  stream = New FileStream("Photo" & UserID & ".bmp", FileMode.OpenOrCreate, FileAccess.Write)             
        writer = New BinaryWriter(stream)
        startIndex = 0 
      retval = ObjDr.GetBytes(1, startIndex, outByte,  0, bufferSize)    While retval = bufferSize             
  writer.Write(outByte)           
 writer.Flush()                         
     ' Reposition start index to end of last buffer and fill buffer. 
            
 startIndex += bufferSize;        
 retval = reader.GetBytes(1, startIndex, outByte,  0, bufferSize)  
 End While
   ' Write the    remaining buffer. writer.Write(outByte, 0, (int)retval - 1);             
writer.Flush();
    writer.Close();
stream.Close()
End While    
ObjDr.Close()  
ObjConnObjConn.Close()

The SqlDataReader class defines a lightweight yet powerful object that is used to read information from a SQL database. A SqlDataReader object has a small footprint, because it doesn't contain more than a single record in memory at any time. This makes it ideal for reading large amounts of data from a database.