ASP.NET – Database Access

ASP.NET – Database Access ”; Previous Next ASP.NET allows the following sources of data to be accessed and used: Databases (e.g., Access, SQL Server, Oracle, MySQL) XML documents Business Objects Flat files ASP.NET hides the complex processes of data access and provides much higher level of classes and objects through which data is accessed easily. These classes hide all complex coding for connection, data retrieving, data querying, and data manipulation. ADO.NET is the technology that provides the bridge between various ASP.NET control objects and the backend data source. In this tutorial, we will look at data access and working with the data in brief. Retrieve and display data It takes two types of data controls to retrieve and display data in ASP.NET: A data source control – It manages the connection to the data, selection of data, and other jobs such as paging and caching of data etc. A data view control – It binds and displays the data and allows data manipulation. We will discuss the data binding and data source controls in detail later. In this section, we will use a SqlDataSource control to access data and a GridView control to display and manipulate data in this chapter. We will also use an Access database, which contains the details about .Net books available in the market. Name of our database is ASPDotNetStepByStep.mdb and we will use the data table DotNetReferences. The table has the following columns: ID, Title, AuthorFirstName, AuthorLastName, Topic, and Publisher. Here is a snapshot of the data table: Let us directly move to action, take the following steps: (1) Create a web site and add a SqlDataSourceControl on the web form. (2) Click on the Configure Data Source option. (3) Click on the New Connection button to establish connection with a database. (4) Once the connection is set up, you may save it for further use. At the next step, you are asked to configure the select statement: (5) Select the columns and click next to complete the steps. Observe the WHERE, ORDER BY, and the Advanced buttons. These buttons allow you to provide the where clause, order by clause, and specify the insert, update, and delete commands of SQL respectively. This way, you can manipulate the data. (6) Add a GridView control on the form. Choose the data source and format the control using AutoFormat option. (7) After this the formatted GridView control displays the column headings, and the application is ready to execute. (8) Finally execute the application. The content file code is as given: <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”dataaccess.aspx.cs” Inherits=”datacaching.WebForm1″ %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title> Untitled Page </title> </head> <body> <form id=”form1″ runat=”server”> <div> <asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString= “<%$ ConnectionStrings:ASPDotNetStepByStepConnectionString%>” ProviderName= “<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString.ProviderName %>” SelectCommand=”SELECT [Title], [AuthorLastName], [AuthorFirstName], [Topic] FROM [DotNetReferences]”> </asp:SqlDataSource> <asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” CellPadding=”4″ DataSourceID=”SqlDataSource1″ ForeColor=”#333333″ GridLines=”None”> <RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ /> <Columns> <asp:BoundField DataField=”Title” HeaderText=”Title” SortExpression=”Title” /> <asp:BoundField DataField=”AuthorLastName” HeaderText=”AuthorLastName” SortExpression=”AuthorLastName” /> <asp:BoundField DataField=”AuthorFirstName” HeaderText=”AuthorFirstName” SortExpression=”AuthorFirstName” /> <asp:BoundField DataField=”Topic” HeaderText=”Topic” SortExpression=”Topic” /> </Columns> <FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” /> <PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” /> <SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ /> <HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” /> <EditRowStyle BackColor=”#999999″ /> <AlternatingRowStyle BackColor=”White” ForeColor=”#284775″ /> </asp:GridView> </div> </form> </body> </html> Print Page Previous Next Advertisements ”;

ASP.NET – First Example

ASP.NET – First Example ”; Previous Next An ASP.NET page is made up of a number of server controls along with HTML controls, text, and images. Sensitive data from the page and the states of different controls on the page are stored in hidden fields that form the context of that page request. ASP.NET runtime controls the association between a page instance and its state. An ASP.NET page is an object of the Page or inherited from it. All the controls on the pages are also objects of the related control class inherited from a parent Control class. When a page is run, an instance of the object page is created along with all its content controls. An ASP.NET page is also a server side file saved with the .aspx extension. It is modular in nature and can be divided into the following core sections: Page Directives Code Section Page Layout Page Directives The page directives set up the environment for the page to run. The @Page directive defines page-specific attributes used by ASP.NET page parser and compiler. Page directives specify how the page should be processed, and which assumptions need to be taken about the page. It allows importing namespaces, loading assemblies, and registering new controls with custom tag names and namespace prefixes. Code Section The code section provides the handlers for the page and control events along with other functions required. We mentioned that, ASP.NET follows an object model. Now, these objects raise events when some events take place on the user interface, like a user clicks a button or moves the cursor. The kind of response these events need to reciprocate is coded in the event handler functions. The event handlers are nothing but functions bound to the controls. The code section or the code behind file provides all these event handler routines, and other functions used by the developer. The page code could be precompiled and deployed in the form of a binary assembly. Page Layout The page layout provides the interface of the page. It contains the server controls, text, inline JavaScript, and HTML tags. The following code snippet provides a sample ASP.NET page explaining Page directives, code section and page layout written in C#: <!– directives –> <% @Page Language=”C#” %> <!– code section –> <script runat=”server”> private void convertoupper(object sender, EventArgs e) { string str = mytext.Value; changed_text.InnerHtml = str.ToUpper(); } </script> <!– Layout –> <html> <head> <title> Change to Upper Case </title> </head> <body> <h3> Conversion to Upper Case </h3> <form runat=”server”> <input runat=”server” id=”mytext” type=”text” /> <input runat=”server” id=”button1″ type=”submit” value=”Enter…” OnServerClick=”convertoupper”/> <hr /> <h3> Results: </h3> <span runat=”server” id=”changed_text” /> </form> </body> </html> Copy this file to the web server root directory. Generally it is c:iNETputwwwroot. Open the file from the browser to execute it and it generates following result: Using Visual Studio IDE Let us develop the same example using Visual Studio IDE. Instead of typing the code, you can just drag the controls into the design view: The content file is automatically developed. All you need to add is the Button1_Click routine, which is as follows: protected void Button1_Click(object sender, EventArgs e) { string buf = TextBox1.Text; changed_text.InnerHtml = buf.ToUpper(); } The content file code is as given: <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”firstexample._Default” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title> Untitled Page </title> </head> <body> <form id=”form1″ runat=”server”> <div> <asp:TextBox ID=”TextBox1″ runat=”server” style=”width:224px”> </asp:TextBox> <br /> <br /> <asp:Button ID=”Button1″ runat=”server” Text=”Enter…” style=”width:85px” onclick=”Button1_Click” /> <hr /> <h3> Results: </h3> <span runat=”server” id=”changed_text” /> </div> </form> </body> </html> Execute the example by right clicking on the design view and choosing ”View in Browser” from the popup menu. This generates the following result: Print Page Previous Next Advertisements ”;

ASP.NET – Environment

ASP.NET – Environment Setup ”; Previous Next ASP.NET provides an abstraction layer on top of HTTP on which the web applications are built. It provides high-level entities such as classes and components within an object-oriented paradigm. The key development tool for building ASP.NET applications and front ends is Visual Studio. In this tutorial, we work with Visual Studio 2008. Visual Studio is an integrated development environment for writing, compiling, and debugging the code. It provides a complete set of development tools for building ASP.NET web applications, web services, desktop applications, and mobile applications. Installation Microsoft provides a free version of visual studio which also contains SQL Server and it can be downloaded from www.visualstudio.com. Step 1 − Once downloading is complete, run the installer. The following dialog will be displayed. Step 2 − Click on the Install button and it will start the installation process. Step 3 − Once the installation process is completed successfully, you will see the following dialog. Close this dialog and restart your computer if required. Step 4 − Open Visual Studio from start Menu which will open the following dialog. It will be a while for the first time for preparation. Step 5 − Once all is done you will see the main window of Visual studio. Let’s create a new project from File → New → Project The Visual Studio IDE The new project window allows choosing an application template from the available templates. When you start a new web site, ASP.NET provides the starting folders and files for the site, including two files for the first web form of the site. The file named Default.aspx contains the HTML and asp code that defines the form, and the file named Default.aspx.cs (for C# coding) or the file named Default.aspx.vb (for VB coding) contains the code in the language you have chosen and this code is responsible for the actions performed on a form. The primary window in the Visual Studio IDE is the Web Forms Designer window. Other supporting windows are the Toolbox, the Solution Explorer, and the Properties window. You use the designer to design a web form, to add code to the control on the form so that the form works according to your need, you use the code editor. Working with Views and Windows You can work with windows in the following ways: To change the Web Forms Designer from one view to another, click on the Design or source button. To close a window, click on the close button on the upper right corner and to redisplay, select it from the View menu. To hide a window, click on its Auto Hide button. The window then changes into a tab. To display again, click the Auto Hide button again. To change the size of a window, just drag it. Adding Folders and Files to your Website When a new web form is created, Visual Studio automatically generates the starting HTML for the form and displays it in Source view of the web forms designer. The Solution Explorer is used to add any other files, folders or any existing item on the web site. To add a standard folder, right-click on the project or folder under which you are going to add the folder in the Solution Explorer and choose New Folder. To add an ASP.NET folder, right-click on the project in the Solution Explorer and select the folder from the list. To add an existing item to the site, right-click on the project or folder under which you are going to add the item in the Solution Explorer and select from the dialog box. Projects and Solutions A typical ASP.NET application consists of many items: the web content files (.aspx), source files (.cs files), assemblies (.dll and .exe files), data source files (.mdb files), references, icons, user controls and miscellaneous other files and folders. All these files that make up the website are contained in a Solution. When a new website is created. VB2008 automatically creates the solution and displays it in the solution explorer. Solutions may contain one or more projects. A project contains content files, source files, and other files like data sources and image files. Generally, the contents of a project are compiled into an assembly as an executable file (.exe) or a dynamic link library (.dll) file. Typically a project contains the following content files: Page file (.aspx) User control (.ascx) Web service (.asmx) Master page (.master) Site map (.sitemap) Website configuration file (.config) Building and Running a Project You can execute an application by: Selecting Start Selecting Start Without Debugging from the Debug menu, pressing F5 Ctrl-F5 The program is built meaning, the .exe or the .dll files are generated by selecting a command from the Build menu. Print Page Previous Next Advertisements ”;

ASP.NET – Server Controls

ASP.NET – Server Controls ”; Previous Next Controls are small building blocks of the graphical user interface, which include text boxes, buttons, check boxes, list boxes, labels, and numerous other tools. Using these tools, the users can enter data, make selections and indicate their preferences. Controls are also used for structural jobs, like validation, data access, security, creating master pages, and data manipulation. ASP.NET uses five types of web controls, which are: HTML controls HTML Server controls ASP.NET Server controls ASP.NET Ajax Server controls User controls and custom controls ASP.NET server controls are the primary controls used in ASP.NET. These controls can be grouped into the following categories: Validation controls – These are used to validate user input and they work by running client-side script. Data source controls – These controls provides data binding to different data sources. Data view controls – These are various lists and tables, which can bind to data from data sources for displaying. Personalization controls – These are used for personalization of a page according to the user preferences, based on user information. Login and security controls – These controls provide user authentication. Master pages – These controls provide consistent layout and interface throughout the application. Navigation controls – These controls help in navigation. For example, menus, tree view etc. Rich controls – These controls implement special features. For example, AdRotator, FileUpload, and Calendar control. The syntax for using server controls is: <asp:controlType ID =”ControlID” runat=”server” Property1=value1 [Property2=value2] /> In addition, visual studio has the following features, to help produce in error-free coding: Dragging and dropping of controls in design view IntelliSense feature that displays and auto-completes the properties The properties window to set the property values directly Properties of the Server Controls ASP.NET server controls with a visual aspect are derived from the WebControl class and inherit all the properties, events, and methods of this class. The WebControl class itself and some other server controls that are not visually rendered are derived from the System.Web.UI.Control class. For example, PlaceHolder control or XML control. ASP.Net server controls inherit all properties, events, and methods of the WebControl and System.Web.UI.Control class. The following table shows the inherited properties, common to all server controls: Property Description AccessKey Pressing this key with the Alt key moves focus to the control. Attributes It is the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control. BackColor Background color. BindingContainer The control that contains this control”s data binding. BorderColor Border color. BorderStyle Border style. BorderWidth Border width. CausesValidation Indicates if it causes validation. ChildControlCreated It indicates whether the server control”s child controls have been created. ClientID Control ID for HTML markup. Context The HttpContext object associated with the server control. Controls Collection of all controls contained within the control. ControlStyle The style of the Web server control. CssClass CSS class DataItemContainer Gets a reference to the naming container if the naming container implements IDataItemContainer. DataKeysContainer Gets a reference to the naming container if the naming container implements IDataKeysControl. DesignMode It indicates whether the control is being used on a design surface. DisabledCssClass Gets or sets the CSS class to apply to the rendered HTML element when the control is disabled. Enabled Indicates whether the control is grayed out. EnableTheming Indicates whether theming applies to the control. EnableViewState Indicates whether the view state of the control is maintained. Events Gets a list of event handler delegates for the control. Font Font. Forecolor Foreground color. HasAttributes Indicates whether the control has attributes set. HasChildViewState Indicates whether the current server control”s child controls have any saved view-state settings. Height Height in pixels or %. ID Identifier for the control. IsChildControlStateCleared Indicates whether controls contained within this control have control state. IsEnabled Gets a value indicating whether the control is enabled. IsTrackingViewState It indicates whether the server control is saving changes to its view state. IsViewStateEnabled It indicates whether view state is enabled for this control. LoadViewStateById It indicates whether the control participates in loading its view state by ID instead of index. Page Page containing the control. Parent Parent control. RenderingCompatibility It specifies the ASP.NET version that the rendered HTML will be compatible with. Site The container that hosts the current control when rendered on a design surface. SkinID Gets or sets the skin to apply to the control. Style Gets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control. TabIndex Gets or sets the tab index of the Web server control. TagKey Gets the HtmlTextWriterTag value that corresponds to this Web server control. TagName Gets the name of the control tag. TemplateControl The template that contains this control. TemplateSourceDirectory Gets the virtual directory of the page or control containing this control. ToolTip Gets or sets the text displayed when the mouse pointer hovers over the web server control. UniqueID Unique identifier. ViewState Gets a dictionary of state information that saves and restores the view state of a server control across multiple requests for the same page. ViewStateIgnoreCase It indicates whether the StateBag object is case-insensitive. ViewStateMode Gets or sets the view-state mode of this control. Visible It indicates whether a server control is visible. Width Gets or sets the width of the Web server control. Methods of the Server Controls The following table provides the methods of the server controls: Method Description AddAttributesToRender Adds HTML attributes and styles that need to be rendered to the specified HtmlTextWriterTag. AddedControl Called after a child control is added to the Controls collection of the control object. AddParsedSubObject Notifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control”s control collection. ApplyStyleSheetSkin Applies the style properties defined in the page style sheet to the control. ClearCachedClientID Infrastructure. Sets the cached ClientID value to null. ClearChildControlState Deletes the control-state information for the server control”s child controls. ClearChildState Deletes the view-state and control-state information for all

ASP.NET – Directives

ASP.NET – Directives ”; Previous Next ASP.NET directives are instructions to specify optional settings, such as registering a custom control and page language. These settings describe how the web forms (.aspx) or user controls (.ascx) pages are processed by the .Net framework. The syntax for declaring a directive is: <%@ directive_name attribute=value [attribute=value] %> In this section, we will just introduce the ASP.NET directives and we will use most of these directives throughout the tutorials. The Application Directive The Application directive defines application-specific attributes. It is provided at the top of the global.aspx file. The basic syntax of Application directive is: <%@ Application Language=”C#” %> The attributes of the Application directive are: Attributes Description Inherits The name of the class from which to inherit. Description The text description of the application. Parsers and compilers ignore this. Language The language used in code blocks. The Assembly Directive The Assembly directive links an assembly to the page or the application at parse time. This could appear either in the global.asax file for application-wide linking, in the page file, a user control file for linking to a page or user control. The basic syntax of Assembly directive is: <%@ Assembly Name =”myassembly” %> The attributes of the Assembly directive are: Attributes Description Name The name of the assembly to be linked. Src The path to the source file to be linked and compiled dynamically. The Control Directive The control directive is used with the user controls and appears in the user control (.ascx) files. The basic syntax of Control directive is: <%@ Control Language=”C#” EnableViewState=”false” %> The attributes of the Control directive are: Attributes Description AutoEventWireup The Boolean value that enables or disables automatic association of events to handlers. ClassName The file name for the control. Debug The Boolean value that enables or disables compiling with debug symbols. Description The text description of the control page, ignored by compiler. EnableViewState The Boolean value that indicates whether view state is maintained across page requests. Explicit For VB language, tells the compiler to use option explicit mode. Inherits The class from which the control page inherits. Language The language for code and script. Src The filename for the code-behind class. Strict For VB language, tells the compiler to use the option strict mode. The Implements Directive The Implement directive indicates that the web page, master page or user control page must implement the specified .Net framework interface. The basic syntax for implements directive is: <%@ Implements Interface=”interface_name” %> The Import Directive The Import directive imports a namespace into a web page, user control page of application. If the Import directive is specified in the global.asax file, then it is applied to the entire application. If it is in a page of user control page, then it is applied to that page or control. The basic syntax for import directive is: <%@ namespace=”System.Drawing” %> The Master Directive The Master directive specifies a page file as being the mater page. The basic syntax of sample MasterPage directive is: <%@ MasterPage Language=”C#” AutoEventWireup=”true” CodeFile=”SiteMater.master.cs” Inherits=”SiteMaster” %> The MasterType Directive The MasterType directive assigns a class name to the Master property of a page, to make it strongly typed. The basic syntax of MasterType directive is: <%@ MasterType attribute=”value”[attribute=”value” …] %> The OutputCache Directive The OutputCache directive controls the output caching policies of a web page or a user control. The basic syntax of OutputCache directive is: <%@ OutputCache Duration=”15″ VaryByParam=”None” %> The Page Directive The Page directive defines the attributes specific to the page file for the page parser and the compiler. The basic syntax of Page directive is: <%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” Trace=”true” %> The attributes of the Page directive are: Attributes Description AutoEventWireup The Boolean value that enables or disables page events that are being automatically bound to methods; for example, Page_Load. Buffer The Boolean value that enables or disables HTTP response buffering. ClassName The class name for the page. ClientTarget The browser for which the server controls should render content. CodeFile The name of the code behind file. Debug The Boolean value that enables or disables compilation with debug symbols. Description The text description of the page, ignored by the parser. EnableSessionState It enables, disables, or makes session state read-only. EnableViewState The Boolean value that enables or disables view state across page requests. ErrorPage URL for redirection if an unhandled page exception occurs. Inherits The name of the code behind or other class. Language The programming language for code. Src The file name of the code behind class. Trace It enables or disables tracing. TraceMode It indicates how trace messages are displayed, and sorted by time or category. Transaction It indicates if transactions are supported. ValidateRequest The Boolean value that indicates whether all input data is validated against a hardcoded list of values. The PreviousPageType Directive The PreviousPageType directive assigns a class to a page, so that the page is strongly typed. The basic syntax for a sample PreviousPagetype directive is: <%@ PreviousPageType attribute=”value”[attribute=”value” …] %> The Reference Directive The Reference directive indicates that another page or user control should be compiled and linked to the current page. The basic syntax of Reference directive is: <%@ Reference Page =”somepage.aspx” %> The Register Directive The Register derivative is used for registering the custom server controls and user controls. The basic syntax of Register directive is: <%@ Register Src=”~/footer.ascx” TagName=”footer” TagPrefix=”Tfooter” %> Print Page Previous Next Advertisements ”;

ASP.NET – Event Handling

ASP.NET – Event Handling ”; Previous Next An event is an action or occurrence such as a mouse click, a key press, mouse movements, or any system-generated notification. A process communicates through events. For example, interrupts are system-generated events. When events occur, the application should be able to respond to it and manage it. Events in ASP.NET raised at the client machine, and handled at the server machine. For example, a user clicks a button displayed in the browser. A Click event is raised. The browser handles this client-side event by posting it to the server. The server has a subroutine describing what to do when the event is raised; it is called the event-handler. Therefore, when the event message is transmitted to the server, it checks whether the Click event has an associated event handler. If it has, the event handler is executed. Event Arguments ASP.NET event handlers generally take two parameters and return void. The first parameter represents the object raising the event and the second parameter is event argument. The general syntax of an event is: private void EventName (object sender, EventArgs e); Application and Session Events The most important application events are: Application_Start – It is raised when the application/website is started. Application_End – It is raised when the application/website is stopped. Similarly, the most used Session events are: Session_Start – It is raised when a user first requests a page from the application. Session_End – It is raised when the session ends. Page and Control Events Common page and control events are: DataBinding – It is raised when a control binds to a data source. Disposed – It is raised when the page or the control is released. Error – It is a page event, occurs when an unhandled exception is thrown. Init – It is raised when the page or the control is initialized. Load – It is raised when the page or a control is loaded. PreRender – It is raised when the page or the control is to be rendered. Unload – It is raised when the page or control is unloaded from memory. Event Handling Using Controls All ASP.NET controls are implemented as classes, and they have events which are fired when a user performs a certain action on them. For example, when a user clicks a button the ”Click” event is generated. For handling events, there are in-built attributes and event handlers. Event handler is coded to respond to an event, and take appropriate action on it. By default, Visual Studio creates an event handler by including a Handles clause on the Sub procedure. This clause names the control and event that the procedure handles. The ASP tag for a button control: <asp:Button ID=”btnCancel” runat=”server” Text=”Cancel” /> The event handler for the Click event: Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click End Sub An event can also be coded without Handles clause. Then, the handler must be named according to the appropriate event attribute of the control. The ASP tag for a button control: <asp:Button ID=”btnCancel” runat=”server” Text=”Cancel” Onclick=”btnCancel_Click” /> The event handler for the Click event: Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) End Sub The common control events are: Event Attribute Controls Click OnClick Button, image button, link button, image map Command OnCommand Button, image button, link button TextChanged OnTextChanged Text box SelectedIndexChanged OnSelectedIndexChanged Drop-down list, list box, radio button list, check box list. CheckedChanged OnCheckedChanged Check box, radio button Some events cause the form to be posted back to the server immediately, these are called the postback events. For example, the click event such as, Button.Click. Some events are not posted back to the server immediately, these are called non-postback events. For example, the change events or selection events such as TextBox.TextChanged or CheckBox.CheckedChanged. The nonpostback events could be made to post back immediately by setting their AutoPostBack property to true. Default Events The default event for the Page object is Load event. Similarly, every control has a default event. For example, default event for the button control is the Click event. The default event handler could be created in Visual Studio, just by double clicking the control in design view. The following table shows some of the default events for common controls: Control Default Event AdRotator AdCreated BulletedList Click Button Click Calender SelectionChanged CheckBox CheckedChanged CheckBoxList SelectedIndexChanged DataGrid SelectedIndexChanged DataList SelectedIndexChanged DropDownList SelectedIndexChanged HyperLink Click ImageButton Click ImageMap Click LinkButton Click ListBox SelectedIndexChanged Menu MenuItemClick RadioButton CheckedChanged RadioButtonList SelectedIndexChanged Example This example includes a simple page with a label control and a button control on it. As the page events such as Page_Load, Page_Init, Page_PreRender etc. take place, it sends a message, which is displayed by the label control. When the button is clicked, the Button_Click event is raised and that also sends a message to be displayed on the label. Create a new website and drag a label control and a button control on it from the control tool box. Using the properties window, set the IDs of the controls as .lblmessage. and .btnclick. respectively. Set the Text property of the Button control as ”Click”. The markup file (.aspx): <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”eventdemo._Default” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title>Untitled Page</title> </head> <body> <form id=”form1″ runat=”server”> <div> <asp:Label ID=”lblmessage” runat=”server” > </asp:Label> <br /> <br /> <br /> <asp:Button ID=”btnclick” runat=”server” Text=”Click” onclick=”btnclick_Click” /> </div> </form> </body> </html> Double click on the design view to move to the code behind file. The Page_Load event is automatically created without any code in it. Write down the following self-explanatory code lines: using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; namespace eventdemo { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblmessage.Text += “Page load event handled. <br />”; if (Page.IsPostBack) { lblmessage.Text +=

ASP.NET – ADO.net

ADO.NET ”; Previous Next ADO.NET provides a bridge between the front end controls and the back end database. The ADO.NET objects encapsulate all the data access operations and the controls interact with these objects to display data, thus hiding the details of movement of data. The following figure shows the ADO.NET objects at a glance: The DataSet Class The dataset represents a subset of the database. It does not have a continuous connection to the database. To update the database a reconnection is required. The DataSet contains DataTable objects and DataRelation objects. The DataRelation objects represent the relationship between two tables. Following table shows some important properties of the DataSet class: Properties Description CaseSensitive Indicates whether string comparisons within the data tables are case-sensitive. Container Gets the container for the component. DataSetName Gets or sets the name of the current data set. DefaultViewManager Returns a view of data in the data set. DesignMode Indicates whether the component is currently in design mode. EnforceConstraints Indicates whether constraint rules are followed when attempting any update operation. Events Gets the list of event handlers that are attached to this component. ExtendedProperties Gets the collection of customized user information associated with the DataSet. HasErrors Indicates if there are any errors. IsInitialized Indicates whether the DataSet is initialized. Locale Gets or sets the locale information used to compare strings within the table. Namespace Gets or sets the namespace of the DataSet. Prefix Gets or sets an XML prefix that aliases the namespace of the DataSet. Relations Returns the collection of DataRelation objects. Tables Returns the collection of DataTable objects. The following table shows some important methods of the DataSet class: Methods Description AcceptChanges Accepts all changes made since the DataSet was loaded or this method was called. BeginInit Begins the initialization of the DataSet. The initialization occurs at run time. Clear Clears data. Clone Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data. Copy Copies both structure and data. CreateDataReader() Returns a DataTableReader with one result set per DataTable, in the same sequence as the tables appear in the Tables collection. CreateDataReader(DataTable[]) Returns a DataTableReader with one result set per DataTable. EndInit Ends the initialization of the data set. Equals(Object) Determines whether the specified Object is equal to the current Object. Finalize Free resources and perform other cleanups. GetChanges Returns a copy of the DataSet with all changes made since it was loaded or the AcceptChanges method was called. GetChanges(DataRowState) Gets a copy of DataSet with all changes made since it was loaded or the AcceptChanges method was called, filtered by DataRowState. GetDataSetSchema Gets a copy of XmlSchemaSet for the DataSet. GetObjectData Populates a serialization information object with the data needed to serialize the DataSet. GetType Gets the type of the current instance. GetXML Returns the XML representation of the data. GetXMLSchema Returns the XSD schema for the XML representation of the data. HasChanges() Gets a value indicating whether the DataSet has changes, including new, deleted, or modified rows. HasChanges(DataRowState) Gets a value indicating whether the DataSet has changes, including new, deleted, or modified rows, filtered by DataRowState. IsBinarySerialized Inspects the format of the serialized representation of the DataSet. Load(IDataReader, LoadOption, DataTable[]) Fills a DataSet with values from a data source using the supplied IDataReader, using an array of DataTable instances to supply the schema and namespace information. Load(IDataReader, LoadOption, String[]) Fills a DataSet with values from a data source using the supplied IDataReader, using an array of strings to supply the names for the tables within the DataSet. Merge() Merges the data with data from another DataSet. This method has different overloaded forms. ReadXML() Reads an XML schema and data into the DataSet. This method has different overloaded forms. ReadXMLSchema(0) Reads an XML schema into the DataSet. This method has different overloaded forms. RejectChanges Rolls back all changes made since the last call to AcceptChanges. WriteXML() Writes an XML schema and data from the DataSet. This method has different overloaded forms. WriteXMLSchema() Writes the structure of the DataSet as an XML schema. This method has different overloaded forms. The DataTable Class The DataTable class represents the tables in the database. It has the following important properties; most of these properties are read only properties except the PrimaryKey property: Properties Description ChildRelations Returns the collection of child relationship. Columns Returns the Columns collection. Constraints Returns the Constraints collection. DataSet Returns the parent DataSet. DefaultView Returns a view of the table. ParentRelations Returns the ParentRelations collection. PrimaryKey Gets or sets an array of columns as the primary key for the table. Rows Returns the Rows collection. The following table shows some important methods of the DataTable class: Methods Description AcceptChanges Commits all changes since the last AcceptChanges. Clear Clears all data from the table. GetChanges Returns a copy of the DataTable with all changes made since the AcceptChanges method was called. GetErrors Returns an array of rows with errors. ImportRows Copies a new row into the table. LoadDataRow Finds and updates a specific row, or creates a new one, if not found any. Merge Merges the table with another DataTable. NewRow Creates a new DataRow. RejectChanges Rolls back all changes made since the last call to AcceptChanges. Reset Resets the table to its original state. Select Returns an array of DataRow objects. The DataRow Class The DataRow object represents a row in a table. It has the following important properties: Properties Description HasErrors Indicates if there are any errors. Items Gets or sets the data stored in a specific column. ItemArrays Gets or sets all the values for the row. Table Returns the parent table. The following table shows some important methods of the DataRow class: Methods Description AcceptChanges Accepts all changes made since this method was called. BeginEdit Begins edit operation. CancelEdit Cancels edit operation. Delete Deletes the DataRow. EndEdit Ends the edit operation. GetChildRows Gets the child rows of this row. GetParentRow Gets the parent row. GetParentRows Gets parent rows of

ASP.NET – Basic Controls

ASP.NET – Basic Controls ”; Previous Next In this chapter, we will discuss the basic controls available in ASP.NET. Button Controls ASP.NET provides three types of button control: Button : It displays text within a rectangular area. Link Button : It displays text that looks like a hyperlink. Image Button : It displays an image. When a user clicks a button, two events are raised: Click and Command. Basic syntax of button control: <asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Click” / > Common properties of the button control: Property Description Text The text displayed on the button. This is for button and link button controls only. ImageUrl For image button control only. The image to be displayed for the button. AlternateText For image button control only. The text to be displayed if the browser cannot display the image. CausesValidation Determines whether page validation occurs when a user clicks the button. The default is true. CommandName A string value that is passed to the command event when a user clicks the button. CommandArgument A string value that is passed to the command event when a user clicks the button. PostBackUrl The URL of the page that is requested when the user clicks the button. Text Boxes and Labels Text box controls are typically used to accept input from the user. A text box control can accept one or more lines of text depending upon the settings of the TextMode attribute. Label controls provide an easy way to display text which can be changed from one execution of a page to the next. If you want to display text that does not change, you use the literal text. Basic syntax of text control: <asp:TextBox ID=”txtstate” runat=”server” ></asp:TextBox> Common Properties of the Text Box and Labels: Property Description TextMode Specifies the type of text box. SingleLine creates a standard text box, MultiLIne creates a text box that accepts more than one line of text and the Password causes the characters that are entered to be masked. The default is SingleLine. Text The text content of the text box. MaxLength The maximum number of characters that can be entered into the text box. Wrap It determines whether or not text wraps automatically for multi-line text box; default is true. ReadOnly Determines whether the user can change the text in the box; default is false, i.e., the user can not change the text. Columns The width of the text box in characters. The actual width is determined based on the font that is used for the text entry. Rows The height of a multi-line text box in lines. The default value is 0, means a single line text box. The mostly used attribute for a label control is ”Text”, which implies the text displayed on the label. Check Boxes and Radio Buttons A check box displays a single option that the user can either check or uncheck and radio buttons present a group of options from which the user can select just one option. To create a group of radio buttons, you specify the same name for the GroupName attribute of each radio button in the group. If more than one group is required in a single form, then specify a different group name for each group. If you want check box or radio button to be selected when the form is initially displayed, set its Checked attribute to true. If the Checked attribute is set to true for multiple radio buttons in a group, then only the last one is considered as true. Basic syntax of check box: <asp:CheckBox ID= “chkoption” runat= “Server”> </asp:CheckBox> Basic syntax of radio button: <asp:RadioButton ID= “rdboption” runat= “Server”> </asp: RadioButton> Common properties of check boxes and radio buttons: Property Description Text The text displayed next to the check box or radio button. Checked Specifies whether it is selected or not, default is false. GroupName Name of the group the control belongs to. List Controls ASP.NET provides the following controls Drop-down list, List box, Radio button list, Check box list, Bulleted list. These control let a user choose from one or more items from the list. List boxes and drop-down lists contain one or more list items. These lists can be loaded either by code or by the ListItemCollection editor. Basic syntax of list box control: <asp:ListBox ID=”ListBox1″ runat=”server” AutoPostBack=”True” OnSelectedIndexChanged=”ListBox1_SelectedIndexChanged”> </asp:ListBox> Basic syntax of drop-down list control: <asp:DropDownList ID=”DropDownList1″ runat=”server” AutoPostBack=”True” OnSelectedIndexChanged=”DropDownList1_SelectedIndexChanged”> </asp:DropDownList> Common properties of list box and drop-down Lists: Property Description Items The collection of ListItem objects that represents the items in the control. This property returns an object of type ListItemCollection. Rows Specifies the number of items displayed in the box. If actual list contains more rows than displayed then a scroll bar is added. SelectedIndex The index of the currently selected item. If more than one item is selected, then the index of the first selected item. If no item is selected, the value of this property is -1. SelectedValue The value of the currently selected item. If more than one item is selected, then the value of the first selected item. If no item is selected, the value of this property is an empty string (“”). SelectionMode Indicates whether a list box allows single selections or multiple selections. Common properties of each list item objects: Property Description Text The text displayed for the item. Selected Indicates whether the item is selected. Value A string value associated with the item. It is important to notes that: To work with the items in a drop-down list or list box, you use the Items property of the control. This property returns a ListItemCollection object which contains all the items of the list. The SelectedIndexChanged event is raised when the user selects a different item from a drop-down list or list box. The ListItemCollection The ListItemCollection object is a collection of ListItem objects. Each ListItem object represents one item in the list. Items in a ListItemCollection are numbered from 0. When the items into a

ASP.NET – Client Side

ASP.NET – Client Side ”; Previous Next ASP.NET client side coding has two aspects: Client side scripts : It runs on the browser and in turn speeds up the execution of page. For example, client side data validation which can catch invalid data and warn the user accordingly without making a round trip to the server. Client side source code : ASP.NET pages generate this. For example, the HTML source code of an ASP.NET page contains a number of hidden fields and automatically injected blocks of JavaScript code, which keeps information like view state or does other jobs to make the page work. Client Side Scripts All ASP.NET server controls allow calling client side code written using JavaScript or VBScript. Some ASP.NET server controls use client side scripting to provide response to the users without posting back to the server. For example, the validation controls. Apart from these scripts, the Button control has a property OnClientClick, which allows executing client-side script, when the button is clicked. The traditional and server HTML controls have the following events that can execute a script when they are raised: Event Description onblur When the control loses focus onfocus When the control receives focus onclick When the control is clicked onchange When the value of the control changes onkeydown When the user presses a key onkeypress When the user presses an alphanumeric key onkeyup When the user releases a key onmouseover When the user moves the mouse pointer over the control onserverclick It raises the ServerClick event of the control, when the control is clicked Client Side Source Code We have already discussed that, ASP.NET pages are generally written in two files: The content file or the markup file ( .aspx) The code-behind file The content file contains the HTML or ASP.NET control tags and literals to form the structure of the page. The code behind file contains the class definition. At run-time, the content file is parsed and transformed into a page class. This class, along with the class definition in the code file, and system generated code, together make the executable code (assembly) that processes all posted data, generates response, and sends it back to the client. Consider the simple page: <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”clientside._Default” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title> Untitled Page </title> </head> <body> <form id=”form1″ runat=”server”> <div> <asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox> <asp:Button ID=”Button1″ runat=”server” OnClick=”Button1_Click” Text=”Click” /> </div> <hr /> <h3> <asp:Label ID=”Msg” runat=”server” Text=””> </asp:Label> </h3> </form> </body> </html> When this page is run on the browser, the View Source option shows the HTML page sent to the browser by the ASP.Net runtime: <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head> <title> Untitled Page </title> </head> <body> <form name=”form1″ method=”post” action=”Default.aspx” id=”form1″> <div> <input type=”hidden” name=”__VIEWSTATE” id=”__VIEWSTATE” value=”/wEPDwUKMTU5MTA2ODYwOWRk31NudGDgvhhA7joJum9Qn5RxU2M=” /> </div> <div> <input type=”hidden” name=”__EVENTVALIDATION” id=”__EVENTVALIDATION” value=”/wEWAwKpjZj0DALs0bLrBgKM54rGBhHsyM61rraxE+KnBTCS8cd1QDJ/”/> </div> <div> <input name=”TextBox1″ type=”text” id=”TextBox1″ /> <input type=”submit” name=”Button1″ value=”Click” id=”Button1″ /> </div> <hr /> <h3><span id=”Msg”></span></h3> </form> </body> </html> If you go through the code properly, you can see that first two <div> tags contain the hidden fields which store the view state and validation information. Print Page Previous Next Advertisements ”;

ASP.NET – Home

ASP.NET Tutorial PDF Version Quick Guide Resources Job Search Discussion ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites. It allows you to use a full featured programming language such as C# or VB.NET to build web applications easily. This tutorial covers all the basic elements of ASP.NET that a beginner would require to get started. Audience This tutorial has been prepared for the beginners to help them understand basic ASP.NET programming. After completing this tutorial you will find yourself at a moderate level of expertise in ASP.NET programming from where you can take yourself to next levels. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of .NET programming language. As we are going to develop web-based applications using ASP.NET web application framework, it will be good if you have an understanding of other web technologies such as HTML, CSS, AJAX. etc Print Page Previous Next Advertisements ”;