Anda di halaman 1dari 119

Lab Manual ASP.

NET

ASP.NET
ASP.NET, the next version of ASP, is a programming framework used to create enterprise-class Web Applications. These applications are accessible on a global basis leading to efficient information management. The advantage ASP.NET offers is more than just the next version of ASP.

Why ASP.NET?
Since 1995, Microsoft has been constantly working to shift it's focus from Windows-based platforms to the Internet. As a result, Microsoft introduced ASP (Active Server Pages) in November 1996. ASP offered the efficiency of ISAPI applications along with a new level of simplicity that made it easy to understand and use. However, ASP script was an interpreted script and consisted unstructured code and was difficult to debug and maintain. As the web consists of many different technologies, software integration for Web development was complicated and required to understand many different technologies. Also, as applications grew bigger in size and became more complex, the number of lines of source code in ASP applications increased dramatically and was hard to maintain. Therefore, an architecture was needed that would allow development of Web applications in a structured and consistent way. The .NET Framework was introduced with a vision to create globally distributed software with Internet functionality and interoperability. The .NET Framework consists of many class libraries, includes multiple language support and a common execution platform. It's a very flexible foundation on which many different types of top class applications can be developed that do different things. Developing Internet applications with the .NET Framework is very easy. ASP.NET is built into this framework, we can create ASP.NET applications using any of the built-in languages. Unlike ASP, ASP.NET uses the Common Language Runtime (CLR) provided by the .NET Framework. This CLR manages execution of the code we write. ASP.NET code is a compiled CLR code instead of interpreted code (ASP). CLR also allows objects written in different languages to interact with each other. The CLR makes development of Web applications simple.

Advantages Using ASP.NET


o o o o o o o o ASP.NET drastically reduces the amount of code required to build large applications ASP.NET makes development simpler and easier to maintain with an event-driven, server-side programming model ASP.NET pages are easy to write and maintain because the source code and HTML are together The source code is executed on the server. The pages have lots of power and flexibility by this approach The source code is compiled the first time the page is requested. Execution is fast as the Web Server compiles the page the first time it is requested. The server saves the compiled version of the page for use next time the page is requested The HTML produced by the ASP.NET page is sent back to the browser. The application source code you write is not sent and is not easily stolen ASP.NET makes for easy deployment. There is no need to register components because the configuration information is built-in The Web server continuously monitors the pages, components and applications running on it. If it noticies memory leaks, infinite loops, other illegal software or activities, it seamlessly kills those activities and restarts itself

o o o

ASP.NET validates information (validation controls) entered by the user without writing a single line of code ASP.NET easily works with ADO .NET using data-binding and page formatting features ASP.NET applications run fater and counters large volumes of users without performance problems

Differences between ASP.NET and Client-Side Technologies


Client-side refers to the browser and the machine running the browser. Server-side on the other hand refers to a Web server.

Client-Side Scripting
Javascript and VBScript and generally used for Client-side scripting. Client-side scripting executes in the browser after the page is loaded. Using client-side scripting you can add some cool features to your page. Both, HTML and the script are together in the same file and the script is download as part of the page which anyone can view. A client-side script runs only on a browser that supports scripting and specifically the scripting language that is used. Since the script is in the same file as the HTML and as it executes on the machine you use, the page may take longer time to download.

Server-Side Scripting
ASP.NET is purely server-side technology. ASP.NET code executes on the server before it is sent to the browser. The code that is sent back to the browser is pure HTML and not ASP.NET code. Like client-side scripting, ASP.NET code is similar in a way that it allows you to write your code alongside HTML. Unlike client-side scripting, ASP.NET code is executed on the server and not in the browser. The script that you write alongside your HTML is not sent back to the browser and that prevents others from stealing the code you developed.

ASP.NET Features
ASP.NET is not just a simple upgrade or the latest version of ASP. ASP.NET combines unprecedented developer productivity with performance, reliability, and deployment. ASP.NET redesigns the whole process. It's still easy to grasp for new comers but it provides many new ways of managing projects. Below are the features of ASP.NET.

Easy Programming Model


ASP.NET enable an than with easy. Best Explorer. makes building real world Web applications dramatically easier. ASP.NET server controls HTML-like style of declarative programming that let you build great pages with far less code classic ASP. Displaying data, validating user input, and uploading files are all amazingly of all, ASP.NET pages work in all browsers including Netscape, Opera, AOL, and Internet

Flexible Language Options


ASP.NET lets you leverage your current programming language skills. Unlike classic ASP, which supports only interpreted VBScript and JScript, ASP.NET now supports more than 25 .NET languages (built-in support for VB.NET, C#, and JScript.NET), giving you unprecedented flexibility in your choice of language.

Great Tool Support


You can harness the full power of ASP.NET using any text editor, even Notepad. But Visual Studio .NET adds the productivity of Visual Basic-style development to the Web. Now you can visually design ASP.NET Web Forms using familiar drag-drop-doubleclick techniques, and enjoy full-fledged code support including statement completion and color-coding. VS.NET also provides integrated support for debugging and deploying ASP.NET Web applications. The Enterprise versions of Visual Studio .NET deliver life-cycle features to help organizations plan, analyze, design, build, test, and coordinate teams that develop ASP.NET Web applications. These include UML class modeling, database modeling (conceptual, logical, and physical models), testing tools (functional, performance and scalability), and enterprise frameworks and templates, all available within the integrated Visual Studio .NET environment.

Rich Class Framework


Application features that used to be hard to implement, or required a 3rd-party component, can now be added in just a few lines of code using the .NET Framework. The .NET Framework offers over 4500 classes that encapsulate rich functionality like XML, data access, file upload, regular expressions, image generation, performance monitoring and logging, transactions, message queuing, SMTP mail, and much more. With Improved Performance and Scalability ASP.NET lets you use serve more users with the same hardware.

Compiled execution
ASP.NET is much faster than classic ASP, while preserving the "just hit save" update model of ASP. However, no explicit compile step is required. ASP.NET will automatically detect any changes, dynamically compile the files if needed, and store the compiled results to reuse for subsequent requests. Dynamic compilation ensures that your application is always up to date, and compiled execution makes it fast. Most applications migrated from classic ASP see a 3x to 5x increase in pages served.

Rich output caching


ASP.NET output caching can dramatically improve the performance and scalability of your application. When output caching is enabled on a page, ASP.NET executes the page just once, and saves the result in memory in addition to sending it to the user. When another user requests the same page, ASP.NET serves the cached result from memory without re-executing the page. Output caching is configurable, and can be used to cache individual regions or an entire page. Output caching can dramatically improve the performance of data-driven pages by eliminating the need to query the database on every request.

Web-Farm Session State


ASP.NET session state lets you share session data user-specific state values across all machines in your Web farm. Now a user can hit different servers in the Web farm over multiple requests and still have full access to her session. And since business components created with the .NET Framework are free-threaded, you no longer need to worry about thread affinity.

Enhanced Reliability
ASP.NET ensures that your application is always available to your users.

Memory Leak, Deadlock and Crash Protection

ASP.NET automatically detects and recovers from errors like deadlocks and memory leaks to ensure your application is always available to your users. For example, say that your application has a small memory leak, and that after a week the leak has tied up a significant percentage of your server's virtual memory. ASP.NET will detect this condition, automatically start up another copy of the ASP.NET worker process, and direct all new requests to the new process. Once the old process has finished processing its pending requests, it is gracefully disposed and the leaked memory is released. Automatically, without administrator intervention or any interruption of service, ASP.NET has recovered from the error.

Easy Deployment
ASP.NET takes the pain out of deploying server applications. "No touch" application deployment. ASP.NET dramatically simplifies installation of your application. With ASP.NET, you can deploy an entire application as easily as an HTML page, just copy it to the server. No need to run regsvr32 to register any components, and configuration settings are stored in an XML file within the application.

Dynamic update of running application


ASP.NET now lets you update compiled components without restarting the web server. In the past with classic COM components, the developer would have to restart the web server each time he deployed an update. With ASP.NET, you simply copy the component over the existing DLL, ASP.NET will automatically detect the change and start using the new code.

Easy Migration Path


You don't have to migrate your existing applications to start using ASP.NET. ASP.NET runs on IIS sideby-side with classic ASP on Windows 2000 and Windows XP platforms. Your existing ASP applications continue to be processed by ASP.DLL, while new ASP.NET pages are processed by the new ASP.NET engine. You can migrate application by application, or single pages. And ASP.NET even lets you continue to use your existing classic COM business components.

XML Web Services


XML Web services allow applications to communicate and share data over the Internet, regardless of operating system or programming language. ASP.NET makes exposing and calling XML Web Services simple. Any class can be converted into an XML Web Service with just a few lines of code, and can be called by any SOAP client. Likewise, ASP.NET makes it incredibly easy to call XML Web Services from your application. No knowledge of networking, XML, or SOAP is required.

Mobile Web Device Support


ASP.NET Mobile Controls let you easily target cell phones, PDAs and over 80 mobile Web devices. You write your application just once, and the mobile controls automatically generate WAP/WML, HTML, or iMode as required by the requesting device.

ASP.NET Development Environment


Most of the programming languages with which we work require a development environment to code, test and run the programs. You may purchase a copy of that software at your local computer store and work with it. With ASP.NET things are different. ASP.NET is a development technology that is built into the .NET Framework. You can create ASP.NET applications with a simple editor like a notepad. If you prefer to work in a development environment then you have many to choose from. Visual Studio .NET (should

purchase) is one development environment from Microsoft. Another development environment from Microsoft which is prefered by many developers is Microsoft Web Matrix. The best thing about ASP.NET Web Matrix is it's free (available as a 1.4 MB free download) and provides most of the features Visual Studio .NET provides.

Setting Up the Development Environment


As you already know, ASP.NET is based on the CLR, class libraries and other tools which are integrated into the .NET Framework. To develop and run a ASP.NET application you need to have the .NET Framework installed on your machine. .NET Framework comes pre installed with Operating Systems like Windows 2003 Server and Windows XP. For other operating systems (Windows 2000, 98, Me, NT 4.0) you need to instal the .NET Framework manually. You can install .NET Framework manually in two ways: .NET Framework SDK or VS .NET. Installing the .NET Framework with SDK is simple. Download .NET Framework from Microsoft.com and double-click setup file and follow the instructions. Installing .NET Framework with Visual Studio .NET is simple too. When you install Visual Studio .NET (set of five cd's) you will be prompted to insert the disk that contains the .NET Framework.

IIS
To develop a Web Application you need IIS (Internet Information Server) on your machine. IIS comes pre installed in Operating Systems like Windows 2000, XP and 2003. You need to configure IIS to run ASP.NET Web applications. You should configure IIS prior to the installation of Visual Studio .NET software on your machine to avoid errors. In most cases configuring IIS after the installation of VS .NET will result in many errors and unexpected behaviour by the application. By default, IIS creates a folder on the server's hard drive with the name Inetpub. The Inetpub folder contains a subfolder called wwwroot. The wwwroot folder is the root for the Web site. All the ASP.NET applications you develop using VS .NET are saved in this wwwroot folder.

Web Hosting
You also can test and run your applications on a server owned by hosting providers. The host will give you details you need to know to upload files onto his server, test those files, etc. Web Hosting providers charge some amount for providing service. There are some hosting providers who provide some space for a certain period of time on their servers for ASP.NET developers to test their applications free of charge. You can find about them on the resources page of this site.

Visual Studio .NET


Visual Studio .NET consists of five cd's. Please follow the guide lines on installing the software.

ASP.NET Web Matrix


To use Web Matrix you need to download Web Matrix software which is a small 1.4 MB file and run the installation. To use Web Matrix you should have the .NET Framework installed on your machine. Developers who decide to code their applications using ASP .NET Web matrix need not worry about IIS. Web Matrix server comes with it's own built-in server that helps you to test and run your applications.

Database
To develop ASP.NET database applications you need to install SQL Server 2000 or higher or Oracle depending on the database you wish to use. Use of SQL Server with ASP.NET is recommended as it's said that SQL Connections are 70% faster than OLEDB Connections. Also, performance improves dramatically when you use SQL Server with ASP.NET.

Configuring IIS 6.0, ASP.NET in Windows 2003


Windows Server 2003 comes with ASP.NET 1.1 and the latest version of Internet Information Server (IIS) version 6.0. IIS 6.0 and ASP.NET 1.1 are designed to integrate seamlessly. By default IIS 6.0 and ASP.NET 1.1 are not enabled. There are two options for enabling IIS in Windows 2003. Option one is to use the Configure Your Server Wizard and Option two is to manually configure it.

Manually Configuring IIS 6.0 and ASP.NET 1.1


To manually configure IIS, open "Add or Remove Programs" from the Control Panel. The Control Panel looks like the image below.

Click on the Add/Remove Windows Components which will open the Windows Components Wizard as shown in the image below.

Here, you need to highlight and check Application Server and then click the Details button. When you click the details button the Application Server dialog opens and it looks like the image below.

Here, you need to check ASP .NET and Internet Information Services and click OK to return to the Windows Component Wizard. Click Next > from the Windows Component Wizard to begin installing.

When installation is complete you will see the last screen of the Windows Component Wizard.

IIS 6.0 and ASP.NET 1.1 are now configured and available.

Lockdown Mode
When you choose to install IIS, it starts out in highly secure or lockdown mode. This means that many of the sophisticated web service features such as Active Server Pages (ASP), ASP.NET, Web Distributed Authoring and Versioning (WebDAV) and server-side includes (SSI) are not functional. In this lockdown mode nothing works and only static content can be served. To be able to use the said features you can individually enable them by following these steps: o o o o o Open IIS Manager by selecting it from Programs->Administrative Tools->Internet Information Services Manager In the left pane of the IIS Manager expand the node for the web server and click Web Service Extensions In the right pane, you will see a list of web service extensions and the status (Prohibited or Allowed) for each You can right click on the extension name and select Allow to enable it individually If you want to allow all extensions for a specific application, you can select the Allow all Web service extensions for a particular application icon in the Tasks section

The image below displays IIS Manager and gives you an idea of the process explained above.

VS .NET IDE
Visual Studio .NET IDE (Integrated Development Environment) is the Development Environment for all .NET based applications which comes with rich features. VS .NET IDE provides many options and is packed with many features that simplify application development by handling the complexities within it. Visual Studio .NET IDE is an enhancement to all other previous IDEs by Microsoft.

Important Features of Visual Studio .NET IDE


One IDE for all .NET based Projects Visual Studio .NET IDE provides a single environment for developing all types of .NET applications. Applications range from single windows applications to complex n-tier application and rich web applications.

Option to choose from Multiple Programming Languages


You can choose the programming language of your choice to develop applications based on your expertise in that language. You can also incorporate multiple programming languages in one .NET solution and edit that with the IDE.

IDE is Customizable
You can customize the IDE based on your preferences. The My Profile settings allow you to do this. With these settings you can set the IDE screen the way you want, the way the keyboard behaves and you can also filter the help files based on the language of your choice.

Built-in Browser
The IDE comes with a built-in browser that helps you browse the Internet without launching another application. You can look for additional resources, online help files, source codes and much more with this built-in browser feature. When we open Visual Studio.NET from Start->Programs->Microsoft Visual Studio .NET->Microsoft Visual Studio .NET the window that is displayed first is the Start Page, which is shown below. The start Page allows us to select from the most recent projects (last four projects) with which we worked along with other useful resources.

The Integrated Development Environment(IDE) as shown in the image below, is what we actually work with. The IDE is shared by all the languages in Visual Studio. You can view the toolbar towards the left side of the image along with the Solution Explorer window towards the right.

The New Project dialogue box like the one in the image below is used to create a new project specifying it's type allowing us to name the project and also specify it's location under the web server where it is saved. The default location on the hard disk where all ASP .NET projects are saved is C:\Inetpub\wwwroot\

The Solution Explorer Window


The Solution Explorer window gives an overview of the solution we are working with and lists all the files in the project. An image of the Solution Explorer window is shown below.

The Server Explorer Window


The Server Explorer window is a great tool that provides "drag and drop" feature and helps us work with databases in an easy graphical environment. For example, if we drag and drop a database table onto a form, VB .NET automatically creates connection and command objects that are needed to access that table. The image below displays Server Explorer window.

Code Designer Window


Code Designers like the image below allows us to edit and write code. This is the window that opens when we double-click on the Web Form or any control. This is the place where we write all the code for the application. Notice the two drop-down list boxes at the top of the code window in the image below. The left box allows us to select the object's code we are working with and the right box allows us to select the part of code that we want to work. Also notice the "+" and "-" boxes in the code designer. You can use those boxes to display code Visual Basic .NET already created, like, Web Form Designer generated code, etc.

Properties Window The properties window allows us to set properties for various objects. For example, if you want to change the font, font size, backcolor, name, text that appears on a label, textbox, etc, you can do that in this window. Below is the image of properties window. You can view the properties window by selecting View->Properties Window from the main menu or by pressing F4 on the keyboard.

Toolbox Window
The toolbox window is the window that gives us access to all controls, components, etc. As you can see from the image below, the toolbox uses tabs to divide it's contents into categories (Data, Web Forms, Components, HTML, Clipboard Ring and General). The Data tab displays tools for creating datasets and making data connections, the Web Forms tab displays tools for adding Web Server controls to the form, the HTML tab displays tools for adding HTML controls to the form, the General tab is left empty by default and the Clipboard Ring tab displays recent items stored in the clipboard and allows us to select from them.

Dynamic Help Window


The dynamic help window displays help which looks up for things automatically. For example, if you want to get help with a label control, select the label and select Help->Dynamic Help from the main menu. Doing that displays all the information relating to labels. The image below displays that. You can get help relating to anything with this feature. Say, if you want to know more about the Label control, select the label and select Dynamic Help from the Help menu. Doing so displays information about the label control.

Task List Window


The task list window displays all the tasks that VB .NET assumes we still have to finish. You can view the task list window by selecting View->Show tasks->All or View->Other Windows->Task List from the main menu. The image below shows that. Task list displays syntax errors and other errors you normally encounter during coding.

Class View Window


The class view window like the image below is the window that presents solutions and projects in terms of the classes they contain and the members of these classes. Using the class view window also helps us to find a member of a class that we want to work with. As you can notice from the image, the class view window displayed all the methods and events for the controls which are available on the form.

Output Window

The output window as you can see in the image below displays the results of building and running applications.

Object Browser Window


The object browser window allows us to view all the members of an object at once. It lists all the objects in our code and gives us access to them. The image below displays the object browser window. You can view the object browser window by selecting View->Other Windows-> Object Browser from the main menu.

Web Forms
Web Forms are based on ASP.NET. Working with Web Forms is similar to working with Windows Forms. But the difference is that we will create Web pages with Web forms that will be accessible by a Web browser. Web Forms are Web pages that serve as the user interface for a Web application. A Web Forms page presents information to the user in any browser or client device and implements application logic using server-side code. Web Forms are based on the System.Web.UI.Page class. The class hierarchy for the page class is shown below. Object Control TemplateControl Page

Components of Web Forms


In Web Forms pages, the user interface programming is divided into two parts: the visual component (design page) and the logic (code behind page). The visual element is the Web Forms page. The page consists of a file with static HTML, or ASP.NET server controls, or both simultaneously. The Web Forms page works as a container for the static text and the controls we want to display. Using the Visual Studio Web Forms Designer and ASP.NET server controls, we can design the form just like in any Visual Studio application. The logic for the Web Forms page consists of code that we create to interact with the form. The programming logic is in a separate file from the user interface file. This file is the "code-behind" file and has an ".aspx.vb" (VB) or ".aspx.cs" (C-Sharp) extension. The logic we write in the code-behind file can be written in Visual Basic or Visual C#. The code-behind class files for all Web Forms pages in a project are compiled into the project dynamic-link library (.dll) file. The .aspx page file is also compiled, but differently. The first time a user loads the aspx page, ASP.NET automatically generates a .NET class file that represents the page, and compiles it to a second .dll file. The generated class for the aspx page inherits from the code-behind class that was compiled into the project .dll file. When the user requests the Web page URL, the .dll files run on the server and dynamically produces the HTML output for your page. When you open a new ASP.NET Web Application in Visual Studio .NET the form that is loaded (WebForm1.aspx) looks like the image below.

The form opens in design mode and you can switch to HTML view by clicking on the HTML tab.deepak.aspx file in the image above is standard HTML with ASP elements embedded in it. The file looks like the image below.

From the above image notice the Codebehind attribute (second line). The codebehind attribute connects this code to the appropriate Visual Basic or C# code (code behind file). deepak.aspx.vb, the codebehind file for deepak.aspx where you write your logic looks like this: Public Class deepak Inherits System.Web.UI.Page Protected WithEvents TextBox1 As System.Web.UI.WebControls.TextBox Protected WithEvents Button1 As System.Web.UI.WebControls.Button Protected WithEvents Label1 As System.Web.UI.WebControls.Label #Region " Web Form Designer Generated Code " 'This call is required by the Web Form Designer. Private Sub InitializeComponent() End Sub Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs)_ Handles MyBase.Init 'CODEGEN: This method call is required by the Web Form Designer 'Do not modify it using the code editor. InitializeComponent() End Sub #End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_ Handles MyBase.Load 'Put user code to initialize the page here End Sub End Class

Notable Properties of Page Object


Below are some notable properties of Page objects: Application: Gets an application object ClientTarget: Gets/Sets if you want to override automatic browser capabilities detection and handle page rendering for specific browsers ErrorPage: Gets/Sets an error page's URL in case there are unhandled page exceptions IsPostBack: Indicates if a page was created after a client postback or if it is being loaded for the first time IsValid: Indicates if the page validation was successful Request: Gets the current http request object Response: Gets the current http response object Server: Gets the current server object Session: Gets the current session object Site: Gets Web Site data User: Gets data about the user Validators: Gets a collection of validation controls on the page

The ASPX Extension


Many of us wonder why the extension for ASP.NET is .aspx. Well, long time ago, when ASP.NET was being developed at Microsoft it was referred to as ASP+ (ASP Plus). You can't use a "+" symbol in a filename but if you turn the + symbol about 45 degrees, it looks like a x. Microsoft chose .aspx as the extension of ASP+. After the name was changed to ASP.NET, Microsoft did'nt change the extension and left it as aspx.

Web Forms Page Life Cycle


In general, the life cycle for a Web Forms page is similar to that of any Web process that runs on the server. Certain characteristics of Web processing information is passed via HTTP protocol, the stateless nature of Web pages, and so on. However, the ASP.NET page framework performs many Web application services for us. It is important to understand the sequence of events that occur when a Web Forms page is processed.

The Life Cycle of a Web Forms Page


It will be helpful to understand some fundamental characteristics of how Web Forms pages work in Web applications before we examine the details of what goes on inside a page when it is processed.

Round Trips
Most Web pages require processing on the server. For example, consider a products page used to check the availability of a certain product. When a user selects his product and hits the submit button the page must check on the server to see whether the selected product is available or not. This kind of functionality is achieved by handling server control events. Whenever a user interaction requires processing on the server, the Web page is posted back to the server, processed and is returned back to the browser. This sequence is

called round trip. The image below demonstrates server round trip.

In any Web scenario, Web pages are recreated with every round trip. When the server finishes processing and sends the page to the browser, it discards the page information. This frees server resources after each request and a Web application can scale to support hundreds or thousands of simultaneous users. The next time the page is posted, the server starts over in creating and processing it, and for this reason, Web pages are said to be stateless. Stateless means the values of a page's variables and controls are not saved on the server. ASP.NET works around the above said limitations in the following ways: o o o ASP.NET saves page and control properties between round trips. This is referred to as saving the view state of the control. It provides state management facilities so that you can save your own variable and applicationspecific or session-specific information between round trips. It can detect when a form is requested for the first time versus when the form is posted, and allows you to program accordingly. You may want a different behavior during a page postback versus an initial request.

Stages in Web Forms Processing


Stage Page Initialization Means Use The page's Page_Init event is raised, During this event, the ASP.NET page and the page and control view state framework restores the control properties are restored. and postback data. Read and restore values stored previously, Using the Page.IsPostBack property, check whether this is the first time the page is The page's Page_Load event is being processed. If this is the first time the raised. page is being processed then perform initial data binding. Otherwise, restore control values. Read and update control properties. The Validate method of any validator Web server controls is Test the outcome of validation in an event invoked to perform the control's handler specified validation. If the page was called in response to a form event, the corresponding Perform application-specific processing and event handler in the page is called handle the specific event raised. during this stage The Page_Unload event is called Perform final cleanup work. Close files, because the page has finished closing database connections and discard rendering and is ready to be objects. discarded.

User Code Initialization

Validation

Event Handling

Cleanup

Web Application State


A Web page is recreated every time it is posted back to the server. In traditional Web programming this means that all the information within the page and information in the controls is lost with each round trip. To overcome this limitation of traditional Web programming, the ASP.NET page framework includes various options to help us preserve changes. One option involves keeping information on the client, directly in the page or in a cookie and another option involves storing information on the server between round trips. We will take a look at both the options.

Saving State in the Client


If we decide to save data in the client then that data is not stored on the server. This means that the page has to store all the data in controls so that it can be sent back to the server when the page is posted back to the server. The different ways in which you can save state in a client are discussed below:

HTML Hidden Form Fields


The default way of saving the state of the data is to use HTML hidden fields. A hidden field stores text data with the HTML <input style="hidden">. A hidden field will not be visibe in the browser but we can set its properties just like we set properties for other standard controls. When a page is posted to the server, the content of a hidden field is sent in the HTTP Form collection along with the values of other controls. In order for hidden field values to be available during page processing, we must submit the page using an HTTP post method. That is, you cannot take advantage of hidden fields if a page is processed in response to a link or HTTP GET method.

Cookies

A cookie is a small text file that stores data on the client's machine or is persistent in-memory during the client browser session. It contains page-specific information the server sends to the client along with page output. Cookies can be temporary with specific expiration times and dates or persistent. We can use cookies to store information about a particular client, session, or application. Cookies are saved on client machine, and when the browser requests a page, it sends the information in the cookie along with the request information. The server can read the cookie and extract its value. Cookies are a relatively secure way of maintaining user-specific data as the browser can only send the data back to the server that originally created the cookie.

Query Strings
A query string is information added to the end of a page's URL. For example, it looks like the following: http://www.startvbdotnet.com/listbooks.aspx?category=asp&price=50 In the above URL , the query string starts with the question mark (?) and includes two attribute-value pairs, one called "category" and the other called "price." Query strings provide a simple and limited way of maintaining state information. Most browsers impose a 255-character limit on the length of the URL. Also, as the query values are exposed to the Internet via the URL, in some cases security may be an issue. In order for query string values to be available during page processing, we must submit the page using an HTTP get method. You cannot take advantage of a query string if a page is processed in response to an HTTP post method.

View State
The Control.ViewState property provides a way for retaining values between multiple requests for the same page. This is the method that the page uses to preserve page and control property values between round trips. When a page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. When the page is posted back to the server, the page parses the view state string at page initialization and restores property information in the page.

Saving State on the Server


We can also save an application's state on the server. Saving an application's state on the server provides with more security than client-side options. The different ways in which you can save state in a server are discussed below:

Application State
An application's state is stored using the application's state object (HttpApplicationState class) for each active Web Application. Application state is a global storage mechanism accessible from all pages in the Web application and is useful for storing information that needs to be maintained between server round trips and between pages. Application state is a key-value dictionary structure created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests. Once you add your application-specific information to application state, the server manages it for you.

Session State
Besides application state, ASP.NET also can store session states using a session state object (HttpSessionState class) for each active Web Application. Session state is similar to application state, but it is scoped to the current browser session. If different users are using an application, each user will have a different session state. If a user leaves the application and returns later, that user will have a different

session state. Session state is a key-value dictionary structure for storing session-specific information that needs to be maintained between server round trips and between requests for pages. Once we add our application-specific information to session state, the server manages this object for us. Depending on the options we specify, session information can be stored in cookies, an out-of-process server, or a SQL Server.

Using Database
Maintaining state using database is a very common method when storing user-specific information where the information store is large. Database storage is particularly useful for maintaining long-term state or state that must be preserved even if the server must be restarted. The database approach is often used along with cookies. For example, when a user access an application, he might need to enter a username/password to log in. You can look up the user in your database and then pass a cookie to the user. The cookie might contain only the ID of the user in your database. You can then use the cookie in the requests that follow to find the user information in the database as needed.

ASP.NET Project Files


In this page we will take a close look at the files that are created as part of a Web Application. When you open a new Web Application in Visual Studio .NET, in the Solution Explorer Window you will notice the following files that are already created as part of the Application: AssemblyInfo.vb, Global.asax, Style.css, Web.Config, Projectname.vsdisco and WebForm.aspx.

AssemblyInfo.vb
An assembly is the building block of an ASP.NET application. The AssemblyInfo.vb file contains information about the assembly, it's version number, dependencies, etc. The AssemblyInfo.vb file looks as follows: Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. <Assembly: AssemblyTitle("")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("")> <Assembly: AssemblyCopyright("")> <Assembly: AssemblyTrademark("")> <Assembly: CLSCompliant(True)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("6ACEB232-291B-4EEC-8462-FEBD203D084B")> ' Version information for an assembly consists of the following four values:

Global.asax
The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level events raised by ASP.NET or by HTTP modules. The Global.asax file

resides in the root directory of an ASP.NET based application. At run time, Global.asax is parsed and compiled into a dynamically generated .NET Framework class derived from the HttpApplication base class. The Global.asax file itself is configured so that any direct URL request for it is automatically rejected. External users cannot download or view the code written within it. The Global.asax file is optional. If you do not define the file, the ASP.NET page framework assumes that you have not defined any application or session event handlers. The Global.asax file looks as follows: Imports System.Web Imports System.Web.SessionState Imports System.Diagnostics Public Class Global Inherits System.Web.HttpApplication #Region " Component Designer Generated Code " #End Region Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) ' Fires when the application is started End Sub Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs) ' Fires when the session is started End Sub Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) ' Fires at the beginning of each request End Sub Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs) ' Fires upon attempting to authenticate the use End Sub Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) End Sub Sub Session_End(ByVal sender As Object, ByVal e As EventArgs) ' Fires when the session ends End Sub

Sub Application_End(ByVal sender As Object, ByVal e As EventArgs) ' Fires when the application ends End Sub End Class

Style.css

The Style.css file is a cascading style sheet file that holds styles for the page. Using this file you can customize the appearance of your Web pages as it sets the styles used. You can define your own styles in this file and use them in your Web pages. To use style sheets a good working knowledge of HTML is essential. The Style.css file looks as follows:

/* Default CSS Stylesheet for a new Web Application project */ BODY { BACKGROUND-COLOR: white; FONT-FAMILY: Verdana, Helvetica, sans-serif; FONT-SIZE: .8em; FONT-WEIGHT: normal; LETTER-SPACING: normal; TEXT-TRANSFORM: none; WORD-SPACING: normal } H1, H2, H3, H4, H5, TH, THEAD, TFOOT { COLOR: #003366; } TFOOT, THEAD { font-size: 1em; word-spacing: normal; letter-spacing: normal; text-transform: none; font-family: Arial, Helvetica, sans-serif; } A:link { text-decoration: none; color: #3333cc; } A:visited { text-decoration: none; color: #333399; } A:active { text-decoration: none; color: #333399; } A:hover { text-decoration: underline; color: #3333cc; } 'Most of the Style.css file is omitted for the purpose of explanation. 'You can find the full file in your Web Applciation project

Web.Config

The Web.Config file is an XML based file that contains configuration information for ASP.NET resources. This file contains information about how the server will handle your application. You can set options for security, permissions, tracing, etc in this file. The Web.Config file looks like this:

<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <!-- DYNAMIC DEBUG COMPILATION Set compilation debug="true" to insert debugging symbols (.pdb information) into the compiled page. Because this creates a larger file that executes more slowly, you should set this value to true only when debugging and to false at all other times. For more information, refer to the documentation about debugging ASP.NET files. --> <compilation defaultLanguage="vb" debug="true" /> <!-- CUSTOM ERROR MESSAGES Set customErrors mode="On" or "RemoteOnly" to enable custom error messages, "Off" to disable. Add <error> tags for each of the errors you want to handle. --> <authentication mode="Windows" /> <!-- AUTHORIZATION This section sets the authorization policies of the application. You can allow or deny access to application resources by user or role. Wildcards: "*" mean everyone, "?" means anonymous (unauthenticated) users. --> <authorization> <allow users="*" /> <!-- Allow all users --> <!-- <allow users="[comma separated list of users]" roles="[comma separated list of roles]"/> <deny users="[comma separated list of users]" roles="[comma separated list of roles]"/> --> </authorization> <!-- APPLICATION-LEVEL TRACE LOGGING Application-level tracing enables trace log output for every page within an application. Set trace enabled="true" to enable application trace logging. If pageOutput="true", the trace information will be displayed at the bottom of each page. Otherwise, you can view the application trace log by browsing the "trace.axd" page from your web application root. --> <trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" /> <!-- SESSION STATE SETTINGS By default ASP.NET uses cookies to identify which requests belong to a particular session. If cookies are not available, a session can be tracked by adding a session identifier to the URL. To disable cookies, set sessionState cookieless="true" --> <sessionState

mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=sa;password=" cookieless="false" timeout="20" /> <!-- GLOBALIZATION This section sets the globalization settings of the application. --> <globalization requestEncoding="utf-8" responseEncoding="utf-8" /> </system.web> </configuration>

WebForm1.aspx, WebForm1.aspx.vb
The WebForm1.aspx file is the file with which you work. You design the interface for your application, write client-side scripts in this file. The WebForm1.aspx.vb file the code behind where you write all the logic for the application that is processed back on the server.

Web Forms Working with Forms


Well, now let's start working with ASP.NET. This site works with ASP.NET using VB. To open a new ASP.NET Web application, open Visual Studio .NET and from the main menu select File->New Project. From the New Project dialogue click on Visual Basic Projects under project types and ASP.NET Web Application under templates. It looks like the image below.

The page that opens looks like the image below.

The page is opened in grid layout mode. To change it to flow layout mode you need to set the pageLayout property to flow layout in the properties window. To view the properties window for the page select View-> Properties Window from main menu or hold F4 key on your keyboard.

Your First ASP.NET Program


On to the Web Form drag a Label and a Button from the toolbox. Double-click the button to open it's event. Write the following code in the click event of the button.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click Label1.Text = "Welcome to ASP.NET" End Sub

The above said code displays "Welcome to ASP.NET" on a label web server control. You can run the sample at the bottom of this page. As mentioned before, working with ASP.NET using VB is like working with VB itself. Everything you do here is what you do with a VB Windows application. Initializing a Web Form We use the Page_Load event to initialize a Web Form. The code you place in this event is executed first and all the code you write performs some function on the page when it is loaded. The Page_Load event looks like this in code: Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_ Handles MyBase.Load 'Put user code to initialize the page here End Sub Live Code Demo

Welcome to ASP.NET
Button

Adding a New Form


To add a new form to the project, select Project->Add Web Form from the main menu or right-click on the project in the Solution Explorer Window and from the context menu select Add->Add Web Form. The dialogue that appears using both the approaches looks like the image below. You also can add a HTML page to the project with the same procedure.

Setting the Startup Form


Consider a Web Application containing more than one page. Setting a Startup form means setting one of the pages in the Application to execute when the application is set to run. To understand that consider the image below.

Notice from the above image, the project Startvbdotnet has more than one Web form. To set the form button.aspx as the start page, select button.aspx, right-click it and select Set As Start Page from the context menu. When you do that, the page buton.aspx is executed and is displayed when you run the application.

Web Page Properties


The table below summarizes properties of the Web page. Properties are listed alphabetically as seen in the properties window. Property ALink AspCompat Background Bgcolor BgProperties BottomMargin Buffer Charset Description Gets/Sets the color of all active links in the page Gets/Sets whether the page is enabled for ASP compatibility Gets/Sets the background image for the page Gets/Sets the background color for the page Gets/Sets the background property for the background image Gets/Sets the bottom margin for the body of the page Gets/Sets response buffering Gets/Sets the character set used to encode the page

ClientTarget Codepage ContentType Culture Debug DefaultClientScript Description Dir enableSessionState enableViewState enableViewStateMac errorPage keywords language Lcid leftMargin Link pageLayout responseEncoding rightMargin showGrid smartNavigation Src targetSchema Text Title topMargin Trace traceMode transaction uiCulture VLink WarningLevel

Gets/Sets user agent string that sets rendering of server controls Gets/Sets locale code page of the file Gets/Sets HTTP-content type output for the page Gets/Sets the culture setting for the page Enables to compile the page with debug symbols or not Gets/Sets the default scripting language for event handlers Gets/Sets the description for the page Gets/Sets the reading order for the page Allows to enable or disable session state Allows to maintain view state across pages Indicates whether view state should be MAC checked Gets/Sets an error page for unhandled requests Gets/Sets keywords for document indexing Gets/Sets the language used for compiling inline code blocks Locale identifier Gets/Sets left margin for the body of the page Gets/Sets the color for unvisited links on the page Gets/Sets the page layout mode for the document Gets/Sets response encoding for content Gets/Sets right margin for the body of the page Shows grid in grid layout items Enables smart IE5 page navigation history Gets/Sets the code behind class to compile Gets/Sets flavor of HTML used Gets/Sets the foreground color for the page Gets/Sets the title for the page Gets/Sets the top margin for the body of the page Gets/Sets whether page level tracing is enabled or not Gets/Sets the trace output mode Gets/Sets the page transaction semantics Gets/Sets culture for resource lookups Gets/Sets the color for visited links on the page Used to handle compiler warnings as errors

Functions Variables
Variables are used to store data. A variable has a name to which we refer and the data type, the type of data the variable holds. You need to declare variables before using them. Variables are declared with the Dim keyword and Dim stands for Dimension.

Variables Sample
The following code creates two variables, adds them and stores the sum in a third variable.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles MyBase.Load Dim x As Integer = 10 Dim y As Integer = 20 Dim z As Integer = x + y Response.Write("Sum is" & " " & z) End Sub

Constants
When we have certain values that we frequently use while programming, we should use Constants. A value declared as constant is of fixed value that cannot be changed once set. Constants should be declared as Public if we want it to be accessed by all parts of the application. We use the Const keyword to declare a constant. The following line of code declares a constant: Public Const Pi as Double=3.14159265

SubProcedures
Procedures are a series of statements that are executed when called. Procedures makes us handle the code in a simple and organized fashion. Sub procedures are procedures which do not return a value. Each time when the Sub procedure is called, the statements within it are executed until the matching End Sub is encountered. The Page_Load event, which is the starting point of the program itself is a sub procedure. When the application starts execution, the control is transferred to Page_Load procedure automatically which is called by default. SubProcedures Sample Private Sub Page_Load(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles MyBase.Load Display() 'control looks for a sub procedure named Display() and executes it End Sub Sub Display() Response.Write("In Sub Procedure") End Sub

Functions
Function is a Procedure which returns a value. Functions are used to evaluate data, make calculations, or to transform data. Declaring a Function is similar to declaring a Sub procedure but functions are declared with the Function keyword. The following is an example on Functions. This simple application is an online loan repayment calculator that asks the user to enter the amount he wants to borrow, the duration of the loan and based on that information calculates his monthly repayments. To start, drag four labels, two textboxes and a button from the toolbox on to the Web Forms page. Open the code designer and paste the following code. Look at Live Code demo towards the botom of this page for user interface design.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click Calc() 'when the user submits his data, control passes to Calc function

End Sub Public Function Calc() As Long Dim amt, temp, temp1, totinterest, mi, mitemp, tot As Double 'declaring the required variables temp = CInt(TextBox1.Text) * 13 'multiplying the amount the user wants to borrow with 13.Assuming the 'interest rate to be 13% totinterest = temp / 100 'calculating the interest amount for the amount entered mitemp = CInt(TextBox2.Text) * 12 'multipling the years entered with 12 to get the number of months mi = totinterest / mitemp 'calculating monthly interest temp1 = CInt(TextBox2.Text) * 12 'multipling the years entered with 12 to get the number of months amt = CInt(TextBox1.Text) / temp1 'dividing the amount borrowed with number of months it is borrowed for tot = amt + mi 'calculating the total by adding the amount + monthly interest Label1.Text = "Your monthly repayment is:" & " " & Int(tot) disp() End Function Public Sub Disp() Label4.Text = "Not Satisfied? Would you like to try another option?" End Sub

Loops
For Loop The For loop is the most popular loop. For loops enables us to execute a series of expressions multiple numbers of times. The For loop needs a loop index, which counts the number of loop iterations as the loop executes. For Loop Sample The following code demonstrates for loop. Private Sub ForLoop_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles ForLoop.Click 'assuming you have a button named ForLoop Dim i As Integer For i = 1 To 5 Response.Write("Welcome to ASP.NET") Next i End Sub

Do Loop

The Do loop can be used to execute a fixed block of statements indefinite number of times. The Do loop keeps executing it's statements while or until the condition is true. Two keywords while and until can be used with the do loop. The Do loop also supports an Exit Do statement which makes the loop to exit at any moment. Do Loop Sample The following code demonstrates Do loop. Private Sub DoWhile_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles DoWhile.Click 'assuming you have a button named DoWhile Dim x As Integer x=0 Do Until x = 10 x=x+1 Response.Write(x) Loop End Sub

If....Then....Else Statement
If conditional expression is one of the most useful control structures which allows us to execute a expression if a condition is true and execute a different expression if it is False. If the condition is true the statements following the Then keyword will be executed, else the statements following the ElseIf will be checked and if true, will be executed, else the statements in the else part will be executed. If Then Sample The following code demonstrates If..Then..Else conditional statement. It asks the user to enter a number between 1 and 3 in a textbox and checks for the number entered using the If..Then..Else statement and displays some text if the condition is true. Private Sub IfThen_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles IfThen.Click If CInt(TextBox1.Text) = 1 Then Label1.Text = "You entered" & CInt(TextBox1.Text) ElseIf CInt(TextBox1.Text) = 2 Then Label1.Text = "You entered" & CInt(TextBox2.Text) ElseIf CInt(TextBox1.Text) = 3 Then Label1.Text = "You entered" & CInt(TextBox2.Text) Else Label1.Text = "You entered another number" End If End Sub

Select Case Statement


Select Case is similar to If..Then..Else statement. Select Case allows us to do various comparisions against one variable that we use throughout the whole statement. Select Case is cleaner and easier to understand if you are continually comparing against one variable. Select Case Sample The following sample asks the user to enter a vowel in a textbox and checks the value entered using the the Select Case statement and if true displays some text. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles Button1.Click Select Case TextBox1.Text Case "a" Label1.text = "You entered A" Case "e" Label1.Text = "You entered E" Case "i" Label1.Text = "You entered I" Case "o" Label1.Text = "You entered O" Case "u" Label1.Text = "You entered U" End Select End Sub

Arrays, Strings
Arrays An array is a way of declaring a whole group of variables at once. Arrays are programming constructs that store data and allow us to access them by numeric index or subscript. Arrays helps us create shorter and simpler code in many situations. Arrays are based on the System.Array namespace. They are declared using Dim, ReDim, Static, Private, Public and Protected keywords. An array can have one dimension or more than one. The dimensionality of an array refers to the number of subscripts used to identify an individual element. An array declaration looks as follows: Dim Sports (5) as String. This single line creates a Sports array that has 6 elements starting from Sports(0) to Sports(5). The first element of an array is always referred by zero index. To change the dimension (redimension) of the Sports array which we already declared we use the following statement: ReDim Sports(20). The size of Sports array changes from 11 to 21. Arrays Sample The following sample will demonstrate arrays. Drag a button and a textbox control on to the Web Forms page. Open the code designer window and paste the following code. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click Dim Sports(5) As String Sports(0)="Tennis" Sports(1) = "Cricket"

Sports(2) = "Rubgy" Sports(3) = "Aussie Rules" Sports(4) = "Soccer" Sports(5) = "Hockey" Label1.Text = "The sport in the location you entered is" & " " &_ Sports(CInt(TextBox1.Text)) End Sub The above sample code creates a Sports array with six elements, asks the user to enter a number between 0 and 5 and displays the sport that is stored in the location (number) the user entered on a label when the button is clicked. Test the code at the bottom of this page for understanding. Strings Strings are supported by the .NET String class. The String data type can represent a series of characters and can contain approximately up to 2 billion Unicode characters. There are many built-in functions in the String class. Some .NET Framework functions are also built into the String class. Some common String functions are discussed below: LCase: Converts a string to lower case UCase: Converts a string to upper case Len: Calculates the number of characters in the string LTrim: Omits spaces that appear on the left-side of the string RTrim: Omits spaces that appear on the right-side of the string Trim: Omits both leading and trailing spaces Clone: Clones a string Concat: Joins two strings Space: Used to create a string with spaces Left: Takes two arguments and returns a string that consists of the left-most characters of the string sent Right: Takes two arguments and returns a string that consists of the right-most characters of the string sent Instr: Searches and returns a shorter string within a long string Replace: Seraches for a small string in a long string and replaces it with the specified string

Sample Application
The following is a simple and interesting sample. It asks the user to enter some information and generates a username and password based on the information entered and displays the newly generated login information to the user. To start, drag six labels, four textboxes and a button control on to the Web Forms page. TextBox1 accepts first name, TextBox2 accepts last name, TextBox3 accepts age and TextBox4 accepts country. Look at the sample below for the user interface. Open the code designer window and paste the following code. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click Dim mystr As String Dim mystr1 As String Dim mystring As String Dim midd As String 'declaring three strings mystr = Left(TextBox1.Text, 3) 'using the left function mystr1 = Right(TextBox2.Text, 3) 'using the right function midd = Mid(TextBox4.Text, 2, 6) & CInt(TextBox3.Text) - 11

'using the mid function mystring = mystr & mystr1 & TextBox3.Text Label5.Text = "Your user name is" & " " & mystring Label6.Text = "Your random password generated by our server is" & " " & midd TextBox1.Visible = False TextBox2.Visible = False TextBox3.Visible = False TextBox4.Visible = False Label1.Visible = False Label2.Visible = False Label3.Visible = False Label4.Visible = False End Sub

Request, Response Objects


Request and Response objects represent information coming into the Web server from the browser and information going out from the server to the browser. The Request object is called the input object and the Response object is called the output object.

Response Object
As mentioned above, the Response object represents a valid HTTP response that was received from the server. The response header properties are read-only. Notable properties of the object are as follows: Body: Gets the body of the HTTP response. Only the portion of the body stored in the response buffer is returned BytesRecv: Gets the number of bytes the client received in the response BytesSent: Gets the number of bytes send in the HTTP request CodePage: Gets or sets the code page used for setting the body of the HTTP response ContentLength: Gets the size, in bytes, of the response body Headers: Gets a collection of headers in the response HeaderSize: Gets the combined size, in bytes, of all the response headers HTTPVersion: Gets the HTTP version used by the server for this response Path: Gets the path that was requested Port: Gets the server port used for the request ResultCode: Gets the server's response status code Server: Gets the name of the server that sent the response TTFB: Gets the number of milliseconds that have passed before the first byte of the response was received TTLB: Gets the number of milliseconds that passed before the last byte of the response was received UseSSL: Checks whether the server and client used an SSL connection for the request and response Sample Code The following sample code assumes that you have a Button control and four RadioButtoin controls with a common GroupName property on a Web Form. The user will be sent to a new Web Page if he makes a selection from one of the radio button's and hits the Submit button. You can view the live demo at the bottom of this page. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles MyBase.Load Dim ccc As String = "Response Object" Response.Write(ccc)

Response.Write("Using Response object") 'using the response object's write method to write some text End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click If RadioButton1.Checked = True Then Response.Redirect("http://www.google.com") 'using the response object's redirect method to redirect the user to another web page ElseIf RadioButton2.Checked = True Then Response.Redirect("http://www.amazon.com") ElseIf RadioButton3.Checked = True Then Response.Redirect("http://www.yahoo.com") ElseIf RadioButton4.Checked = True Then Response.Redirect("http://www.startvbdotnet.com") End If End Sub

Request Object As mentioned above, the Request object represents an HTTP request before it has been sent to the server. Notable properties of this object are as follows: Body: Gets/Sets the HTTP request body CodePage: Gets/Sets the code page for the request body EncodeBody: Gets/Sets whether ACT automatically URL encodes the request body EncodeQueryAsUTF8: Gets/Sets whether ACT automatically UTF-8 encodes the request's query string Headers: Gets the HTTP Headers collection object HTTPVersion: Gets/Sets the HTTP version Path: Gets/Sets the HTTP path ResponseBufferSize: Gets/Sets the size of the buffer used to store the response body Verb: Gets/Sets the HTTP method verb Sample Code Private Sub Page_Load(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles MyBase.Load Dim s As String = Request.UserHostAddress() 'request's user's host address and writes using the response object's write method Response.Write(s) Dim a As String = Request.ApplicationPath() 'request's the application path Response.Write(a) Dim aa As String = Request.Browser.Browser 'request's the type of browser Response.Write(aa) Dim b As String = Request.CurrentExecutionFilePath 'request's the current execution path Response.Write(b)

Dim c As String = Request.FilePath 'request's the path to the file that you are currently working with Response.Write(c) Dim cc As String = Request.HttpMethod 'gets the HttpMethod Response.Write(cc) If Request.Browser.Browser = "IE" Then 'checks to see if the browser is IE and if true displays a message Response.Write("You are using IE") Else Response.Write("You are using some other browser") End If Response.Write("Your computer is/has the following" & Request.Useragent) 'displays the user information about his computer End Sub

Debugging ASP.NET Pages


Errors in programming are inevitable. Everyone of us introduce errors while coding. Errors are normally referred to as bugs. The process of going through the code to identify the cause of errors and fixing them is called Debugging. There are three types of errors: syntax errors, run time errors, logical errors. Error Handling ASP.NET provides support for handling and tracking errors that might occur while developing and testing applications. When we run an ASP.NET application, if an error occurs on the server that processes the page, an HTML error page is generated and displayed to the user in the browser. While error messages are displayed, ASP.NET takes care of the security issues and makes sure that no crucial information is displayed in the browser to the user. Crucial information can be in the form of compiler messages, configuration settings, filenames, stack traces and source code. When an error occurs, an error message is displayed to the user. To see the error details one of the following should be done: Access the page again from the server or modify the configuartion settings in the Web.Config file. Creating Custom Error Pages As mentioned above, when an error occurs with an ASP.NET application, an HTML error page is displayed to the user. You can also create your own error page and display that to the user instead of the HTML error page that is generated. The page which you create is called the Custom error page. To create your own custom error page, open a Web page and insert some text in it or an image or both. The custom error page can be an html page or an aspx page. Once you are finsihed designing your error page you need to modify the Web.Config file of the application so that it redirects the user to the error page created in case an error occurs. The configuration file should be as follows:

<configuration> <system.web> <customErrors mode="RemoteOnly" DefaultRedirect="Error.aspx"/> 'assuming your error page is error.aspx </system.web> </configuration> The mode attribute of the customErrors tag can be set to three values which are as follows: On: Custom error messages are always sent to the user and the detailed ASP.NET error page is not shown Off: Only original messages are sent to the user even if a custom error page is available RemoteOnly: Custom error messages are displayed only to remote users accessing the site. If no custom error page is present then the remote users see a message indicating that an error has occured Setting Status Code Errors While browsing the Internet you might have come across these kind of error messages, Page not Found, You are Not Authorized to View this page, HTTP Error 404 - File or directory not found, etc. This type of errors are called as status code errors and you can set these kind of errors in the ASP.NET Web.Config file. The type of error will be identified by the HTTP status code. The Web.Config file for that looks like this:

Web Controls
A control is an object that can be drawn on to the Web Form to enable or enhance user interaction with the application. Examples of these controls include the TextBoxes, Buttons, Labels, Radio Buttons etc. All these Web server controls are based on the System.Web.UI.Control class and the class hierarchy is as follows: Object Control Notable properties of the Control objects are summarized in the table below: Property ClientID Controls EnableViewState ID Page Parent Site UniqueID Visible Description Gets the ASP.NET control identifier for the control Gets a collection of child controls in a control Gets/Sets whether the control maintains it's state between server round trips Gets/Sets the ID for the control Gets the page object that contains the control Gets the control parent control Gets the control's Web site Gets the Unique ID for the control Gets/Sets whether the control is visible or not

The WebControl Class

Web server controls in ASP.NET are not based directly on the Control class but are based on the WebControl class, which is based on the Control class. The class hierarchy for the WebControl class is as follows: Object Control WebControl Notable properties of the WebControl class are summarized in the table below: Property AccessKey Attributes BackColor BorderColor BorderStyle BorderWidth ControlStyle CssClass Enabled Font ForeColor Height Style TabIndex ToolTip Width Description Gets/Sets the access key for the control Gets a collection of attributes used to render the control Gets/Sets the control's background color Gets/Sets the controls border color Gets/Sets the control's border style Gets/Sets the control's border width Gets the control's style Gets/Sets the control's CSS class Gets/Sets whether the control is enabled Gets/Sets the font for the control Gets/Sets the control's foreground color Gets/Sets the control's height Gets the HTML style of the control as a collection of text attributes Gets/Sets the control's tab index Gets/Sets the control's tool tip text Gets/Sets the control's width

Label
The Label Web Server control is used to label other parts of the application. They are used to display text which the user can't change. To display text on a label we use the text property. The class hierarchy for this control is as follows: Object Control WebControl Label A label control with BorderStyle property as solid and BorderColor property as blue is shown below. I am Label

Literal
A Literal Web Server control doesn't have any visual appearance on a Web Form but is used to insert literal text into a Web Form. This control makes it possible to add HTML code directly in the code designer window without switching to design view and clicking the HTML button to edit the HTML. The class hierarchy for this control is as follows: Object

Control Literal The notable property of this control is the text property which is the text that is inserted into the Web Form. A literal control with text "I am Literal" is displayed below. I am Literal Editing HTML with Literal Control As mentioned above, we can use a literal control to edit the HTML directly in the code designer. The following line of code demonstrates that. Literal1.Text = "<b><u>I am Literal</b></u>" To test the above line of code click the button below. The text "I am Literal" displayed beside the Button will be underlined and will be displayed in bold format. The difference is we added HTML code directly in the code designer window instead of switching and editing it in HTML view.

TextBox
The TextBox Web Server control is used to accept input from the user. They appear like a box and allows the user to enter some text, like, username, password, etc. The class hierarchy for this control is as follows: Object Control WebControl TextBox Below is a ReadOnly TextBox with BackColor property set to Silver, BorderColor property set to Brown and BorderStyle property set to solid.

Notable properties
Notable properties of the TextBox control are as follows: AutoPostBack: Gets/Sets whether events will be automatically posted to the server Columns: Gets/Sets the textbox's width in columns MaxLength: Gets/Sets the maximum number of characters that can be displayed in the textbox ReadOnly: Gets/Sets whether the textbox is readonly Rows: Gets/Sets a multiline textbox's display height Text: Gets/Sets the text in a textbox TextMode: Gets/Sets whether a textbox should be single line, multiline or a password control Wrap: Gets/Sets whether text wraps in a textbox Code Examples

Sample 1

Drag a TextBox and a Button control onto the WebForm. When you click the button some text is displayed in a TextBox. The code for that looks like this: Private Sub Button1_Click(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles Button1.Click TextBox1.Text = "Welcome to TextBoxes" End Sub

Sample2, Multiline TextBox


Drag a TextBox, Button and a Label control onto the form. We will make this TextBox a Multiline textbox and display the text entered in this multiline textbox on a label. Before you proceed, select the textbox, open it's properties window and set it's TextMode property to Multiline. The code to achieve the desired functionality looks like this: Private Sub Button2_Click(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles Button2.Click Label2.Text = TextBox2.Text End Sub

Sample3, Password Character


Drag a Textbox, Button and a Label control onto the form. Select the textbox, open it's properties window and set the TextMode property to Password. When you set TextMode property to password, the text you enter in the textbox is masked with asteriks (*). The following code displays the text you entered in the textbox as text for the label. Private Sub Button3_Click(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles Button3.Click Label3.Text = TextBox3.Text End Sub

Buttons
A Button Web Server control is a control which we click and release to perform some action. The class hierarchy for the Button control is as follows: Object Control WebControl Button Button Event The default event of the Button is the Click event which looks like this in code:

Private Sub Button1_Click(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles Button1.Click 'Implementation Omitted

End Sub Notable Properties CausesValidation: Gets/Sets the button that causes validation CommandArgument: Gets/Sets the command argument which is passed to the command event handler CommandName: Gets/Sets the command name which is passed to the command event handler Text: Gets/Sets the caption on the button

Command Button
To create a command button you need to add a command name to the button. You add a command name to the button with the CommandName property and a command argument with the CommandArgument property. Both these properties can hold text which can be recovered in code. Sample Code1 Drag a Button onto the form from the toolbox and set it's text as ClickMe. When you click the button it changes it's text from ClickMe to "You clicked Me". The code for that looks like this: Private Sub Button1_Click(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles Button1.Click Button1.Text = "You clicked me" End Sub Sample code to create a Command Button Drag two TextBoxes and Buttons from the toolbox. Select Button one and in it's properties window set the CommandName property to Command1 and CommandArgument property to I am Command one. Repeat the same for Button two. When you click Button1, the CommandName of Button1 will be displayed in TextBox1 and CommandArgument of Button2 in TextBox2. To get those values we need to use the command event for the button and not the click event. The code for that looks like this: Private Sub Button1_Command(ByVal sender As System.Object,_ ByVal e As System.Web.UI.WebControls.CommandEventArgs) Handles Button1.Command TextBox1.Text = e.CommandName End Sub Private Sub Button2_Command(ByVal sender As System.Object,_ ByVal e As System.Web.UI.WebControls.CommandEventArgs) Handles Button2.Command TextBox2.Text = e.CommandArgument End Sub

DropDownList
The DropDownList Web server control is same as the ListBox control but it supports only single selection and displays items in a drop-down manner. The class hierarchy for this control is as follows:

Object Control WebControl ListControl DropDownList DropDownList Event The default event of the drop-down list is the SelectedIndexChanged which looks like this in code: Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged 'Implementation Omitted End Sub Notable property of the drop-down list is the Items property with which we add items to the control. Like ListBoxes this control doesn't support multiple selections.

DropDownList Sample
Drag a DropDownList, Button and a TextBox control on to the form. Add some items to the DropDownList control using it's Item property. The following code will display the item selected from the drop-down list in a textbox when the button is clicked. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click TextBox1.Text = "You Selected:" & DropDownList1.SelectedItem.Text End Sub

ListBox
The ListBox Web server control displays a list of items from which we can make a selection. We can select one or more items from the list of items displayed. The class hierarchy for this control is as follows: Object Control WebControl ListControl ListBox

ListBox Event
The default event of the list box is the SelectedIndexChanged which looks like this is code:

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles ListBox1.SelectedIndexChanged 'Implementation Omitted End Sub

Notable Properties of the ListBox are as follows: Items: Gets/Sets the collection of items in the control Rows: Gets/Sets the number of rows in the list box SelectionMode: Gets/Sets the list box's selection mode, can be set to single or multiple ListBox Samples Single Selection ListBox Drag a ListBox, Button and a TextBox control on to the form. Add some items to the ListBox using the Items property. The following lines of code will display the item you select from the list box in a textbox when the button is clicked. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click TextBox1.Text = "You Selected" & " " & ListBox1.SelectedItem.Text End Sub Multiple Selection ListBox Modifying the above sample to make the ListBox allow us to select multiple items, select the ListBox and in it's properties window set the SelectionMode proeprty to Multiple. The following lines of code will display the selected items in the textbox when the button is clicked: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click Dim i As Integer TextBox1.Text = "You Selected" & " " For i = 0 To ListBox1.Items.Count - 1 If ListBox1.Items(i).Selected Then TextBox1.Text = TextBox1.Text & ListBox1.Items(i).Text & " " End If Next End Sub

CheckBox
The CheckBox Web server control gives us an option to select, say, yes/no or true/false. A checkbox is clicked to select and clicked again to deselect some option. When a checkbox is selected, a check (a tick mark) appears indicating a selection. The class hierarchy for this control is as follows: Object Control WebControl CheckBox

CheckBoxEvent
The default event of the CheckBox is the CheckedChanged event which looks like this in code:

Private Sub CheckBox1_CheckedChanged(ByVal System.EventArgs) Handles 'Implementation End Sub Notable Properties Notable properties of the CheckBox are as follows: Checked: Gets/Sets whether a checkbox displays a check Text: Gets/Sets the text caption for the checkbox TextAlign: Gets/Sets the alignment of the text caption CheckBox Sample

sender

As

System.Object, ByVal e As_ CheckBox1.CheckedChanged Omitted

Drag two CheckBoxes, a TextBox and a Button control on to the form. Set the Text property for the CheckBoxes as Male and Female. The following code will display the text of the Checkbox that is checked in the textbox when the button is clicked. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click If CheckBox1.Checked Then TextBox1.Text = "Your Gender" & " " & CheckBox1.Text ElseIf CheckBox2.Checked Then TextBox1.Text = "Your gender " & " " & CheckBox2.Text End If

CheckBoxList
The CheckBoxList Web server control displays a number of checkboxes at once. This control provides a multi selection check box group that can be dynamically generated with data binding. It contains an Items collection with members that correspond to individual items in the list. To determine which items are checked, we need to test the Selected property of each item in the list. The class hierarchy for his control is as follows: Object Control WebControl ListControl CheckBoxList Notable Properties Notable properties of the CheckBoxList control are as follows: Items: Gets/Sets the collection of items in the list RepeatColumns: Gets/Sets the number of displayed columns in the check box list RepeatDirection: Gets/Sets the display direction of checkboxes RepeatLayout: Gets/Sets the checkbox layout TextAlign: Gets/Sets the check box's text alignment CheckBoxList Sample

Drag a CheckBoxList, TextBox and a Button on to the form. Select the CheckBoxList and add some items to it using the Items property. The following code will display the text of the checkbox that is checked in the textbox when the button is clicked. Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click TextBox1.Text = CheckboxList1.SelectedItem.Text End Sub

RadioButtonList
The RadioButtonList Web server control is used to display a list of radio buttons. This control provides us with a single-selection radio button group that can be dynamically generated via data binding. The Items property of this control allows us to add items to the control. To determine which item is selected, we need to test the SelectedItem property of the list. The class hierarchy of this control is as follows: Object Control WebControl ListControl RadioButtonList RadioButtonList event The default event of the RadioButtonList is the SelectedIndexChanged which looks like this in code: Private Sub RadioButtonList1_SelectedIndexChanged(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles RadioButtonList1.SelectedIndexChanged 'Implementation Omitted End Sub Notable Properties Notable properties of the RadioButtonList control are as follows: Items: Gets/Sets the collection of items in the list RepeatColumns: Gets/Sets the number of displayed columns in the radio button list RepeatDirection: Gets/Sets the display direction of radio buttons RepeatLayout: Gets/Sets the radio button layout TextAlign: Gets/Sets the radio button's text alignment RadioButtonListSample Drag a RadioButonList, TextBox and a Buton control on to a form. Add some items to the radio button list with it's item property. The following code will display the item you select in the radio button list in the textbox when you click the button. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click TextBox1.Text = RadioButtonList1.SelectedItem.Text End Sub

RadioButton
The RadioButton Web server control is similar to CheckBox but RadioButtons are displayed as rounded instead of box. The class hierarchy for this control is as follows: Object Control WebControl CheckBox Radiobutton Radiobutton Event The default event of the RadioButton is the CheckedChanged event which looks like this in code: Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles RadioButton1.CheckedChanged 'Implementation Omitted End Sub Notable property of the RadioButton control is the GroupName property which sets the radio button's group. The radio button will act in concert with the other members of the group. RadioButton Sample Drag three radio button's, a textbox and a button on to the form. Select each radio button and set the GroupName property for each to ABC. If you do not set the GroupName property to a common name then each radio button will act differently and when you make a selection all radio buttons will be rounded. In most cases, you want your users to select only one option from a given list and to accompolish that you need to set the GroupName property. The following code will display the text of the radio button selected in a textbox when the button is clicked. Select each radio button and set the Text as shown below and paste the following code: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click If RadioButton1.Checked Then TextBox1.Text = "You heard about us through " & " " & RadioButton1.Text ElseIf RadioButton2.Checked Then TextBox1.Text = "You heard about us through " & " " & RadioButton2.Text ElseIf RadioButton3.Checked Then TextBox1.Text = "You heard about us through " & " " & RadioButton3.Text End If End Sub

Validation Controls
Validation is the process of making sure that the user enters correct information into a form. Validation controls provided by .NET Framework work in the client browser if the browser supports Javascript and

DHTML and checks the data the user entered before sending it to the server. All the validation takes place in the browser and nothing is sent back to the server. If the browser doesn't support DHTML and scripting then validation is done on the server. All validation controls in the .NET Framework are derived from the BaseValidator class. This class serves as the base abstract class for the validation controls and provides the implementation for all validation controls that derive from this class. The validation controls that are provided by the .NET Framework are as follows: RequiredFieldValidator CompareValidator RangeValidator RegularExpressionValidator CustomValidator Common to all the above said controls are the ErrorMessage and ControlToValidate properties. The ErrorMessage property is used to set an error to be displayed and the ControlToValidate property is used to set the control you want to check. RequiredFieldValidator Simplest of all, the RequiredField validator makes sure that the user enters data into a form. For example, on a registration form you might want your users to enter their date of birth in a textbox. If they leave this field empty, this validation control will display an error. The class hierarchy for this control is as follows: Object Control WebControl Label BaseValidator RequiredFieldValidator Notable property of the RequiredFieldValidator is the InitialValue property which sets an initial value in the control. CompareValidator Comparison validators are used to compare the values entered by the user into a control (textbox) with the value entered into another control or with a constant value. We indicate the control to validate by setting the ControlToValidate property and if we want to compare a specific control with another control we need to set the ControlToCompare property to specify the control to compare with. The class hierarchy for this control is as follows: Object Control WebControl Label BaseValidator BaseCompareValidator CompareValidator RangeValidator

Range Validators are used to test if the value of a control is inside a specified range of values. The three main properties of this control are the ControlToValidate property which contains the control to validate and Maximum and Minimum values which hold the maximum and minimum values of the valid range. The class hierarchy for this control is as follows: Object Control WebControl Label BaseValidator BaseCompareValidator RangeValidator RegularExpressionValidator RegularExpression validators are used to check if the value in a control matches a pattern defined by the regular expression. Notable property for this control is the ValidationExpression property which allows us to select a predefined expression which we want to match with the data entered in a control. The class hierarchy for this control is as follows: Object Control WebControl Label BaseValidator RegularExpressionValidator CustomValidator Custom validators are used to perform our own validation for the data in a control. For example, you can check the value entered by a user is even or odd with this control which is not possible with any of the above mentioned validation controls. You write the script for the validation using Javascript or VBScript and associate that script function to the ClientValidationFunction property of this control. The class hierarchy for this control is as follows: Object Control WebControl Label BaseValidator CustomValidator ValidationSummary Validation summary control is used to display a summary of all validation errors (from all validation controls) on a Web page. This class is supported by the ValidationSummary class and the hierarchy is as follows: Object Control WebControl ValidationSummary

Notable property of this control is the DisplayMode property which allows us to display the errors in a specific format, example, as a list, paragraph or as a bulletlist.

ADO .NET
Most applications need data access at one point of time making it a crucial component when working with applications. Data access is making the application interact with a database, where all the data is stored. Different applications have different requirements for database access. ASP.NET uses ADO .NET (Active X Data Object) as it's data access and manipulation protocol which also enables us to work with data on the Internet. ADO.NET Data Architecture Data Access in ADO.NET relies on two components: DataSet and Data Provider. DataSet The dataset is a disconnected, in-memory representation of data. It can be considered as a local copy of the relevant portions of the database. The DataSet is persisted in memory and the data in it can be manipulated and updated independent of the database. When the use of this DataSet is finished, changes can be made back to the central database for updating. The data in DataSet can be loaded from any valid data source like Microsoft SQL server database, an Oracle database or from a Microsoft Access database. Data Provider The Data Provider is responsible for providing and maintaining the connection to the database. A DataProvider is a set of related components that work together to provide data in an efficient and performance driven manner. The .NET Framework currently comes with two DataProviders: the SQL Data Provider which is designed only to work with Microsoft's SQL Server 7.0 or later and the OleDb DataProvider which allows us to connect to other types of databases like Access and Oracle. Each DataProvider consists of the following component classes: The Connection object which provides a connection to the database The Command object which is used to execute a command The DataReader object which provides a forward-only, read only, connected recordset The DataAdapter object which populates a disconnected DataSet with data and performs update

Data access with ADO.NET can be summarized as follows: A connection object establishes the connection for the application with the database. The command object provides direct execution of the command to the database. If the command returns more than a single value, the command object returns a DataReader to provide the data. Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated using the command object or the DataAdapter.

Component classes that make up the Data Providers The Connection Object The Connection object creates the connection to the database. Microsoft Visual Studio .NET provides two types of Connection classes: the SqlConnection object, which is designed specifically to connect to Microsoft SQL Server 7.0 or later, and the OleDbConnection object, which can provide connections to a wide range of database types like Microsoft Access and Oracle. The Connection object contains all of the information required to open a connection to the database. The Command Object The Command object is represented by two corresponding classes: SqlCommand and OleDbCommand. Command objects are used to execute commands to a database across a data connection. The Command objects can be used to execute stored procedures on the database, SQL commands, or return complete

tables directly. Command objects provide three methods that are used to execute commands on the database: ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE or DELETE ExecuteScalar: Returns a single value from a database query ExecuteReader: Returns a result set by way of a DataReader object

The DataReader Object The DataReader object provides a forward-only, read-only, connected stream recordset from a database. Unlike other components of the Data Provider, DataReader objects cannot be directly instantiated. Rather, the DataReader is returned as the result of the Command object's ExecuteReader method. The SqlCommand.ExecuteReader method returns a SqlDataReader object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object. The DataReader can provide rows of data directly to application logic when you do not need to keep the data cached in memory. Because only one row is in memory at a time, the DataReader provides the lowest overhead in terms of system performance but requires the exclusive use of an open Connection object for the lifetime of the DataReader. The DataAdapter Object The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is essentially the middleman facilitating all communication between the database and a DataSet. The DataAdapter is used either to fill a DataTable or DataSet with data from the database with it's Fill method. After the memoryresident data has been manipulated, the DataAdapter can commit the changes to the database by calling the Update method. The DataAdapter provides four properties that represent database commands: SelectCommand InsertCommand DeleteCommand UpdateCommand When the Update method is called, changes in the DataSet are copied back to the database and the appropriate InsertCommand, DeleteCommand, or UpdateCommand is executed. System.Data.OleDb The System.Data.OleDb namespace provides classes that are required to connect to OLE DB data sources. Let's take a look at the classes provided by System.Data.OleDb. OleDbConnection class The System.Data.OleDb.OleDbConnection class represents a connection to OleDb data source. Applications that need to connect to a OleDb data source should use this class. OleDbCommand class The System.Data.OleDb.OleDbCommand class represents a SQL statement or stored procedure that is executed in a database by an OLE DB provider. The OleDbCommand class can be used to create the Select, Insert, Update and Delete commands that need to be sent to the data source.

OleDbDataReader The System.Data.OleDb.OleDbDataReader class creates a data reader. It is used to read a row of data from the database. The data is read as forward-only, read-only stream which means that data is read sequentially, one row after another. The DataReader is independent of the OleDb data source from which the data is retrieved. OleDbDataAdapter The System.Data.OleDb.OleDbDataAdapter acts as a middleman between the application and OleDb data source. We use the Select, Insert, Delete and Update command properties of this class for loading and updating the data. DataSet The System.Data namespace contains a DataSet class which is a disconnected, in-memory representation of data. It can be considered as a local copy of all the relevant portions of the database. The DataSet is persisted in memory and the data in it can be manipulated and updated independent of the database. Code Samples The following code samples will put the System.Data.OleDb namespace and the classes within it to work. The following code samples assume that you have an Access database named Books (Books.mdb) with three columns (BookName, Publisher, ISBN) on the C: drive of your machine. Select Command Open a new Web Forms page, add a Button control to it an paste the following code. Imports System.Data.OleDb 'namespace to be imported Public Class WebForm5 Inherits System.Web.UI.Page #Region " Web Form Designer Generated Code " #End Region Dim myConn As OleDbConnection Dim myComm As OleDbCommand Dim dr As OleDbDataReader Private Sub Select_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Select.Click Try myConn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;_ Data Source=C:\sandeep\books.mdb;") myConn.Open() myComm = New OleDbCommand("Select* from Table1", myConn) dr = myComm.ExecuteReader Do While dr.Read 'reading from the datareader Response.Write(dr(0) & " ") Response.Write(dr(1) & " ") Response.Write(dr(2) & "<br>") 'displaying data from the table

'html break is used to display data in a tabular format Loop Catch End Try End Sub End Class System.Data.OleDb

Insert Command
Add a Button control to the Web Forms page. Assuming you already have a connection established (refer to previous page sample) paste the following code. Private Sub Insert_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Insert.Click Try myConn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;_ Data Source=C:\sandeep\books.mdb;") myConn.Open() myComm = New OleDbCommand("Insert into Table1 values 'ASP.NET ',_ 'McGraw Hill',192435211", myConn) Dim sa As Integer = myComm.ExecuteNonQuery() Response.Write("Records inserted" & " " & sa) myConn.Close() Catch End Try End Sub

Update Command
Add a Button control to the Web Forms page and paste the following code. Private Sub Update_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Update.Click Try myConn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;_ Data Source=C:\sandeep\books.mdb;") myConn.Open() myComm = New OleDbCommand("Update Table1 Set Publisher='MSR'_ where publisher='McGraw Hill'", myConn) Dim sa As Integer = myComm.ExecuteNonQuery() Response.Write("Records updated" & " " & sa) Catch End Try End Sub

Delete Command
Add a Button control to the Web Forms page and paste the following code.

Private Sub Delete_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Delete.Click Try myConn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;_ Data Source=C:\sandeep\books.mdb;") myConn.Open() myComm = New OleDbCommand("Delete from Table1 where isbn=192435211", myConn) Dim sa As Integer = myComm.ExecuteNonQuery() Response.Write("Records deleted" & " " & sa) Catch End Try End Sub System.Data.SqlClient The System.Data.SqlClient namespace provides classes that are required to connect to SQL Server. Let's take a look at the classes provided by System.Data.SqlClient. SqlConnection Class The SqlConnection class represents a connection to SQL Server data source. SqlCommand Class The SqlCommand class represents a SQL statement or stored procedure for use in a database with SQL Server. SqlDataReader The SqlDataReader class creates a data reader to be used with SQL Server. SqlDataAdapter The SqlDataAdapter class represents a bridge between the dataset and the SQL Server database. It includes the Select, Insert, Delete and Update commands for loading and updating the data. Code Samples The following code samples will put the System.Data.SqlClient namespace and the classes within it to work.

Select Command
Open a new Web Forms page, add a Button to it and paste the following code. The following code will display data from Discounts table in Pubs sample database. Imports System.Data.SqlClient Dim myConnection As SqlConnection Dim myCommand As SqlCommand Private Sub Page_Load(ByVal sender As System.Object, ByVal e As_

System.EventArgs) Handles MyBase.Load End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs") 'establishing connection. you need to provide password for sql server Try myConnection.Open() 'opening the connection myCommand = New SqlCommand("Select * from discounts", myConnection) Dim dr As SqlDataReader = myCommand.ExecuteReader() While dr.Read() 'reading from the datareader Response.Write(dr(0).ToString()) Response.Write(dr(1).ToString()) Response.Write(dr(2).ToString()) Response.Write(dr(3).ToString()) Response.Write(dr(4).ToString()) 'displaying data from the table End While dr.Close() myConnection.Close() Catch End Try End Sub

Insert Command
Add a Button control to the Web Forms page and paste the following code. The following code will insert a record into the Jobs table in Pubs sample database.

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles Button2.Click Dim ra As Integer myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs") 'you need to provide password for sql server myConnection.Open() myCommand = New SqlCommand("Insert into Jobs values 12,'IT Manager',100,300 ", myConnection) ra= myCommand.ExecuteNonQuery() 'Since no value is returned we use ExecuteNonQuery Response.Write("Records Inserted" & ra) myConnection.Close() End Sub

Delete Command
Add a Button to the Web Forms page and paste the following code. The following code will delete a record from the Authors table in Pubs sample database.

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button3.Click Dim ss As Integer myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs") myConnection.Open() myCommand = New SqlCommand("Delete from Authors where city='Oakland' ", myConnection) ss = myCommand.ExecuteNonQuery() Response.Write("Records affected" & ss) myConnection.Close() End Sub

Update Command
Add a Button to the Web Forms page and paste the following code. The following code will update a record in Authors table. Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button4.Click Dim sss As Integer myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs") myConnection.Open() myCommand = New SqlCommand("Update Authors Set city='Oakland' where city='San Jose' ",_ myConnection) sss = myCommand.ExecuteNonQuery() Response.Write("Records affected" & sss) myConnection.Close() End Sub

Data Adapter Configuration Wizard


The DataAdapter Configuration wizard let's you customize your data adapter as you want, like displaying the whole table or displaying selected columns from the table and so on. To start, open a new database in Access, name it as books, create a table, Table1 with some fields in it and save the database in the C: drive of your machine. To start creating your own DataAdapter, open a blank form and add a button (Button1) and a DataGrid control to it from the toolbox. Our intention here is to display the table or some columns in the table which we created in Access in the DataGrid control when Button1 is clicked. To do that, click on the Data tab in the toolbox and double-click OleDbDataAdapter object. We are using OleDbDataAdapter here as we are working with an OleDb data source. After you select OleDbDataAdapter from the data tab in the toolbox it gets added to the component tray beneath the Web Forms designer and opens the Data Adapter Configuration wizard dialog box which looks like the image below.

Click the Next> button in the Data Adapter Configuration wizard to select the data connection you want to use. The dialog box that opens up look like the image below.

Since we are working with our own table, select the New Connection button in that dialog box which opens up the Data Link properties dialog. The Data Link Properties dialog looks like the image below.

In the Data Link properties dialog click the Provider tab and select "Microsoft Jet 4.0 OLE DB Provider" from the list of available providers. After selecting the provider from the Provider tab click Next> button to take you to the Connection tab. Click on the ellipse where it says "Select or enter a database name" and browse for the database on the local drive. Since we are working with our own database (Books.mdb) located on the C: drive, select that. Click on the "Test Connection" button to test the connection and if the connection succeeds, click OK. Clicking OK displays a dialog box like the image below.

It's here where we will generate the SQL Statement we use with this data adapter. Click next on this dialog box which takes you to another dialog like the image below.

It's here where we build our SQL Queries. To build your query click the Query Builder button on this dialog. Once you click that button, the Query Builder dialog opens with a list that displays all the tables in the database with which we are working. In this case it displays only one table as we created only one table in the books database. The Query Builder dialog looks like the image below. Select Table1 in this dialog and click Add to add Table1 to the Query Builder dialog. You can select entire table to be displayed in the DataGrid or just some columns. To display entire table in the DataGrid select the checkbox named "All Columns" in the small dialog named "Table1" which automatically builds the SQL statement for us. If you want to display specific columns from the table in the DataGrid, check on the columns you want to display. Once you finish with that, click next.

The dialog

that

opens when

you

click

next

looks

like

the

image

below.

This dialog lists the configuration of the data adapter and lists the results. Click finish to close the Data Adapter Configuration wizard. Data Adapter Configuration Wizard Once you finish configuring your data adapter you can preview the data that will be displayed on the Web Forms page. To preview your data select Data->Preview Data from the main menu which opens the Data Adapter Preview window as displayed in the image below.

On this window select OleDbDataAdapter1 from the Data Adapters drop-down box and click the Fill Dataset button to preview data. Creating DataSet To create a DataSet, select Data->Generate DataSet from the main menu. From the window that opens, select new and check the checkbox for Table1 and also check the checkbox where it says "Add this dataset to the designer" and click OK. Once you click OK, you can see the DataSet, DataSet11 being added to the component tray. The image below displays that.

Drag a DataGrid and a Button control on to the Web Forms page designer from the toolbox. Select the DataGrid and open it's properties window. For the DataSource property select DataSet11 from the list and for the DataMember property select Tabel1. Open the code designer and paste the following code.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click DataSet11.Clear() OleDbDataAdapter1.Fill(DataSet11) End Sub Run the Web Forms page and click the button. The table will be displayed on the data grid. The data grid that displays the data looks pretty plain. You can customize your data grid easily. To do that, select the data grid, right-click on it and from the menu select the Auto Format item to open the Auto Format dialog as shown in the image below. This dialog lets you select from a number of predefined styles for the data grid, setting header color, border color and so on.

Property Builder The Property Builder tool is another way of customizing the data grid. To open Property Builder, rightclick on the data grid and select property builder from the menu. The property builder tool window is shown in the image below. The property builder allows you to display some columns instead of the whole table (which is loaded in the dataset), set border, whether or not to use paging, etc. Paging lets you display a table in pages, where only a few records are visible in a data grid one page at a time. The user will be provided with hyperlinks to see additional pages in which the data grid displays additional records.

Sending Email with ASP.NET


One of the common functionalities used in Web development is sending email from a Web page. A common use of sending email from a Web page is allowing site visitors to fill in comments via an HTML form and send them to the Webmaster. The .NET Framework makes the task of sending email from a Web page relatively simple. In order to send an email from an ASP.NET Web page you need to use the SmtpMail class found in the System.Web.Mail namespace, which contains a static method Send.

Sending Email
The namespace that needs to be imported to send an email is the System.Web.Mail namespace. We use the SmtpMail and MailMessage classes of this namespace for this purpose. The MailMessage class provides properties and methods for constructing an email message. To start, open a Web Forms page, drag a Button control on to the form, switch to code view and paste the following code.

Imports System.Web.Mail 'namespace to be imported Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click Dim mailMessage As New MailMessage() 'creating an instance of the MailMessage class mailMessage.From = "xyz@mydomain.com" 'senders email address mailMessage.To = "abc@sendersemail.com" 'recipient's email address mailMessage.Cc = "carboncopy@sendersemail.com" 'email address of the Cc recipient mailMessage.Bcc = "blindcarboncopy@sendersemail.com" 'email address of the Bcc recipient mailMessage.Subject = "Hello" 'subject of the email message mailMessage.BodyFormat = MailFormat.Text 'message text format. Can be text or html mailMessage.Body = "This tutorial is sending email with an ASP.NET app." 'message body mailMessage.Priority = MailPriority.Normal 'email priority. Can be low, normal or high SmtpMail.SmtpServer = "mail.yourserver.com" 'mail server used to send this email. modify this line based on your mail server SmtpMail.Send(mailMessage) 'using the static method "Send" of the SmtpMail class to send the mail Response.Write("Mail sent") 'message stating the mail is sent End Sub The above code sends an email when the button is clicked. That's fine for the purpose of learning but when you have a feedback form on your Web site with textboxes, labels, etc, you need to slightly modify the above code. The following is the complete, functional code for an ASP.NET page that sends an email to the Webmaster of the site. To start, drag seven labels, six textboxes and two buttons on to the Web forms page designer. The user interface for this sample can be found at the bottom of this page. The modified code looks as follows: Imports System.Web.Mail Private Sub SendMail_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles SendMail.Click Dim mailMessage As New MailMessage() mailMessage.From = TextBox1.Text mailMessage.To = "admin@startvbdotnet.com" 'you also can set this to TextBox2.Text mailMessage.Cc = TextBox3.Text mailMessage.Bcc = TextBox4.Text mailMessage.Subject = TextBox5.Text mailMessage.BodyFormat = MailFormat.Text mailMessage.Body = TextBox6.Text 'textbox6 TextMode property is set to MultiLine mailMessage.Priority = MailPriority.Normal SmtpMail.SmtpServer = "mail.yourserver.com"

'mail server used to send this email. modify this line based on your mail server SmtpMail.Send(mailMessage) Label6.Text = "Your mail was sent" 'message stating the mail is sent End Sub Private Sub Reset_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Reset.Click TextBox1.Text = " " TextBox2.Text = " " TextBox3.Text = " " TextBox4.Text = " " TextBox5.Text = " " TextBox6.Text = " " 'resetting all the value to default i.e null End Sub

CHHATTISGARH SWAMI VIVEKANAND TECHNICAL UNIVERSITY, BHILAI (C.G.)


University List of Experiments to be performed
1. Write a program in ASP.Net using text box , control, multiline text box & password. 2. Write a program in ASP.Net using events in text box. 3. Write a program in ASP.Net using labels, text box & button control. 4. Write a program in ASP.Net using radiobutton 5. Write a program in ASP.Net using checkboxlist. 6. Write a program in ASP.Net using dropdownlist. 7. Write a program in ASP.Net using listbox. 8. Write a program in ASP.Net using dataList controls. 9. Write a program in ASP.Net using dataList controls with styles. 10. Write a program in ASP.Net for validation in textbox. 11. Write a program in ASP.Net for insertion using ADO.NET . 12. Write a program in ASP.Net for Searching using ADO.NET. 13. Write a program in ASP.Net for Deletion using ADO.NET. 14. Write a program in ASP.Net for Updation using ADO.NET. 15. Write a program in ASP.Net using HTML Server Controls. 16. Write a program in ASP.Net using Web Server Controls.

Experiment No. 1
Write a program in ASP.Net using text box control, multiline text box & password. Description: This program shows the implementation of textbox control. This
program takes user name and password from the user and display the full name and password in the message box.

Input/Output

Coding:
Partial Class _Default Inherits System.Web.UI.Page Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles _Button1.Click If TextBox1.Text = "" Or TextBox2.Text = "" The006E MsgBox("Please Enter The User Name and password") Exit Sub End If

MsgBox("The User Name is" & TextBox1.Text & "and the Password is" & TextBox2.Text) End Sub End Class

Assignment Question:
Write a program in ASP.NET to concatenate first name and last name of the user using text box.

Viva Questions:
1) Write all the important properties of a text box control. 2) Which property is used to set the focus of the text box control.

Experiment No. 2
Write a program in ASP.Net using events in text box. Description: This program shows the implementation of textbox control. This
program takes first name and last name from the user and display the full name and in the message box.

Input/Output

Coding:
Partial Class _Default Inherits System.Web.UI.Page Protected Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged MsgBox(TextBox1.Text & " " & TextBox2.Text) End Sub End Class

Assignment Question:
Write a program in ASP.NET to use unload event of a text box.

Viva Question:
Write all the events of a text box control.

Experiment No. 3
Write a program in ASP.Net using labels, text box & button Control. Description: This program takes name, address, email id and phone number
from the user and display the details in the label control.

Input/Output

Coding:
Partial Class _Default Inherits System.Web.UI.Page Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Label6.Text = TextBox1.Text & " Lived in " & TextBox3.Text & " having Mail Id " & TextBox2.Text & " and Call Number is" & TextBox4.Text End Sub End Class

Assignment Question:
Write a program in ASP.NET to implement unload event of a command button.

Viva Question:
Write all the events of a command button control.

Experiment No. 4
Write a program in ASP.Net using Radio button Description: This program show the implementation of radio button. Select
any one option from the radio and the program display the select radio button text in the label control.

Input/Output

Coding:
Partial Class _Default Inherits System.Web.UI.Page Protected Sub RadioButton1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged If RadioButton1.Checked Then Label6.Text = "You selected " & RadioButton1.Text End If End Sub

Protected Sub RadioButton2_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButton2.CheckedChanged If RadioButton2.Checked Then Label6.Text = "You selected " & RadioButton2.Text End If End Sub Protected Sub RadioButton3_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButton3.CheckedChanged If RadioButton3.Checked Then Label6.Text = "You selected " & RadioButton3.Text End If End Sub End Class

Assignment Question:
Write a program in ASP.NET to change the form color using radio button.

Viva Question:
Write all the properties of a command radio button control.

Experiment No. 5
Write a program in ASP.Net using Checkboxlist. Description: This program show the implementation of check box. Select
any one option or more option from the check box and displays all the selected hobbies in the label control.

Input/Output

Coding:
Partial Class _Default Inherits System.Web.UI.Page Protected Sub CheckBoxList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBoxList1.SelectedIndexChanged Dim i Label6.Text = "Your Hobbies Are "

For i = 0 To CheckBoxList1.Items.Count - 1 If CheckBoxList1.Items(i).Selected Then Label6.Text += CheckBoxList1.Items(i).Text & " " End If Next End Sub End Class

Assignment Question:
Write a program in ASP.NET to change the form color using checkbox control.

Viva Question:
Write all the properties of a check button control.

Experiment No. 6
Write a program in ASP.Net using Dropdownlist. Description: This program show the implementation of drop down button. Select
month from the drop down button and displays the number of days in the label control.

Input/Output

Coding:
Partial Class _Default Inherits System.Web.UI.Page Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged Dim i As Integer If DropDownList1.Text = "January" Or DropDownList1.Text = "March" Or DropDownList1.Text = "May" Or DropDownList1.Text = "July" Or

DropDownList1.Text = "August" Or DropDownList1.Text = "October" Or DropDownList1.Text = "December" Then Label6.Text = "31" ElseIf DropDownList1.Text = "April" Or DropDownList1.Text = "June" Or DropDownList1.Text = "September" Or DropDownList1.Text = "November" Then Label6.Text = "30" Else Label6.Text = "28" End If End Sub End Class

Assignment Question:
Write a program in ASP.NET to insert all the days in the drop down button

Viva Question:
Write all the properties of a dropdown button.

Experiment No. 7

Write a program in ASP.Net using Listbox. Description: This program show the implementation of list box button. Select items
from the list box button and displays the selected item in the label control.

Input/Output

Coding:
Partial Class _Default Inherits System.Web.UI.Page Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Label2.Text = "You Selected " & ListBox1.SelectedItem.Text End Sub End Class

Assignment Question:

Write a program in ASP.NET to insert 10 cities in the list box.

Viva Question:
Write all the properties of a listbox.

Experiment No. 8

Write a program in ASP.Net using DataList controls. Description: 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.

Coding:
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 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: <%@ 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>

Assignment Question:
Write a program in ASP.NET to implement the use using database..

Viva Question:
Write all the properties of a data list.

Experiment No. 9

Write a program in ASP.Net using DataList controls with styles. Description: 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.

Coding:
<%@ 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>

Assignment Question:
Write a program in ASP.NET to implement the same using database..

Viva Question:
Write all the properties of a data list using style.

Experiment No. 10

Write a program in ASP.Net for validation in textbox.

Description: 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.

Input/Output

Coding:
Partial Class _Default Inherits System.Web.UI.Page Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click If TextBox1.Text = "" Then MsgBox("Please Enter User Name ") TextBox1.Focus() Exit Sub End If

If IsNumeric(TextBox1.Text) Then MsgBox("Please Enter Correct User Name ") TextBox1.Text = "" TextBox1.Focus() Exit Sub End If If TextBox2.Text = "" Then MsgBox("Please Enter Password") TextBox2.Focus() Exit Sub End If End Sub End Class

Assignment Question:
Write a program in ASP.NET to validate the textbox for numeric values.

Viva Question:
What is validation.

Experiment No. 11
Write a program in ASP.Net for insertion using ADO.NET .

Description: This program implements the use of ADO.NET and insert the basic
details in the database.

Input/Output

Coding:
Imports System.Data.OleDb Partial Class _Default Inherits System.Web.UI.Page Dim cn As New OleDbConnection Dim cmd As New OleDbCommand Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\personal_Details.mdb;Persist Security Info=False"

cmd.Connection = cn cn.Open() End Sub Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim s As String s = "insert into Table1 values('" & Trim(TextBox1.Text) & "','" & T Trim(TextBox2.Text) & "','" & Trim(TextBox3.Text) & "','" & Trim(TextBox4.Text) & "')" cmd.CommandText = s cmd.ExecuteNonQuery() MsgBox("One Record Inserted") End Sub End Class

Assignment Question:
Write a program in ASP.NET to insert the student details into the database.

Viva Question:
What is ADO.Net.

Experiment No. 12
Write a program in ASP.Net for Searching using ADO.NET.

Description: This program implements the use of ADO.NET and search details from
the database.

Input/Output

Coding:
Imports System.Data.OleDb Partial Class _Default Inherits System.Web.UI.Page Dim cn As New OleDbConnection Dim cmd As New OleDbCommand Dim rs As OleDbDataReader Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim str As String cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\personal_Details.mdb;Persist Security Info=False" cmd.Connection = cn cn.Open() Str = "Select * from table1"

cmd.CommandText = str rs = cmd.ExecuteReader Do While (rs.Read()) DropDownList1.Items.Add(rs(0)) Loop rs.Close() End Sub Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "Select * from table1" cmd.CommandText = str rs = cmd.ExecuteReader Do While (rs.Read()) If rs(0) = DropDownList1.Text Then TextBox2.Text = rs(1) TextBox3.Text = rs(2) TextBox4.Text = rs(3) End If Loop rs.Close()

End Sub End Class

Assignment Question:
Write a program in ASP.NET to search the student details into the database.

Viva Question:
How ADO differ from ADO.NET.

Experiment No. 13
Write a program in ASP.Net for updation using ADO.NET.

Description: This program implements the use of ADO.NET and update details
from the database.

Input/Output

Coding:
Imports System.Data.OleDb Partial Class _Default Inherits System.Web.UI.Page Dim cn As New OleDbConnection Dim cmd As New OleDbCommand Dim rs As OleDbDataReader Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim str As String cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\personal_Details.mdb;Persist Security Info=False" cmd.Connection = cn

cn.Open() Str = "Select * from table1" cmd.CommandText = str rs = cmd.ExecuteReader Do While (rs.Read()) DropDownList1.Items.Add(rs(0)) Loop rs.Close() End Sub Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "Select * from table1" cmd.CommandText = str rs = cmd.ExecuteReader Do While (rs.Read()) If rs(0) = DropDownList1.Text Then TextBox2.Text = rs(1) TextBox3.Text = rs(2) TextBox4.Text = rs(3) End If Loop rs.Close() End Sub Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click Dim s As String s = "update Table1 set Address='" & Trim(TextBox2.Text) & "',Call_Number='" & Trim(TextBox3.Text) & "',Email_ID='" & Trim(TextBox4.Text) & "' where Name='" & DropDownList1.Text & "'" cmd.CommandText = s cmd.ExecuteNonQuery() MsgBox("One Record Updated End Sub End Class

Assignment Question:
Write a program in ASP.NET to update the student details into the database.

Viva Question:

What are the advantages using ADO.NET.

Experiment No. 14
Write a program in ASP.Net for deletion using ADO.NET.

Description: This program implements the use of ADO.NET and delete details from
the database.

Input/Output

Coding:
Imports System.Data.OleDb Partial Class _Default Inherits System.Web.UI.Page Dim cn As New OleDbConnection Dim cmd As New OleDbCommand Dim rs As OleDbDataReader Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim str As String cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\personal_Details.mdb;Persist Security Info=False" cmd.Connection = cn cn.Open()

Str = "Select * from table1" cmd.CommandText = str rs = cmd.ExecuteReader Do While (rs.Read()) DropDownList1.Items.Add(rs(0)) Loop rs.Close() End Sub Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "Select * from table1" cmd.CommandText = str rs = cmd.ExecuteReader Do While (rs.Read()) If rs(0) = DropDownList1.Text Then TextBox2.Text = rs(1) TextBox3.Text = rs(2) TextBox4.Text = rs(3) End If Loop rs.Close() End Sub Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click Dim s As String s = "delete from Table1 where Name='" & DropDownList1.Text & "'" cmd.CommandText = s cmd.ExecuteNonQuery() MsgBox("One Record Deleted") End Sub End Class

Assignment Question:
Write a program in ASP.NET to delete the student details from the database.

Viva Question:

What is dataset.

Experiment No. 15
Write a program in ASP.Net using HTML Server Controls. Description: This program implements the use of HTML server controls. Input/Output

Coding:
< % @ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <head runat="server"> <title>Untitled Page</title> <script language="javascript" type="text/javascript"> // <!CDATA[ function Submit1_onclick() { document.write('The Required Name is Deepak Bhalla and Employee Number is 1'); } // ]]> </script> </head> <body> <form id="form1" runat="server"> <div style="font-weight: bold; font-size: large; color: #cc3333"> &nbsp;&nbsp; Employee

Details<br /> <br /> Emp Name &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input id="Text1" type="text" /><br /> <br /> &nbsp;Emp Number &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<input id="Text2" type="text" /> &nbsp;&nbsp;<br /> <br /> <input id="Submit1" size="30" style="font-weight: bold" type="submit" value="submit" lang="vi" onclick="return Submit1_onclick()" onclick="return Submit1_onclick()" /> <input id="Reset1" size="30" style="font-weight: bold" type="reset" value="reset" /></div> </form> </body> </html>

Assignment Question:
Write a program in ASP.NET to server controls.

Viva Question:
What is the difference between Asp and Asp.Net

Experiment No. 16
Write a program in ASP.Net using Web Server Controls. Description: This program implements the use of web server controls. Input/Output

Please enter your name:

Enter

Hi Deepak Bhalla, welcome to ASP.NET!

Coding:
<html> <script language="VB" runat="server"> Sub EnterBtn_Click(Sender As Object, E As EventArgs) Message.Text = "Hi " & Name.Text & ", welcome to ASP.NET!" End Sub </script> <body><!-- #include File="C:\Inetpub\wwwroot\DotNetJunkies\DotNetJunkiesWeb\_js\omni.inc" --> <h3><font face="Verdana">Handling Control Action Events</font></h3> <p> This sample demonstrates how to access a &lt;asp:textbox&gt; server control within the "Click" event of a &lt;asp:button&gt;, and use its content to modify the text of a &lt;asp:label&gt;. <p> <hr> <form action="controls3.aspx" runat=server> <font face="Verdana"> Please enter your name: <asp:textbox id="Name" runat=server/> <asp:button text="Enter" Onclick="EnterBtn_Click" runat=server/> <p> <asp:label id="Message" runat=server/>

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

Assignment Question :
Write a program in ASP.Net to do validation using server controls.

Viva Question:
What is the difference berween HTML web controls and ASP.Net web server controls. ***********************************************************************

Anda mungkin juga menyukai