Sie sind auf Seite 1von 24

BCA – 5th Semester ASP DOT NET Notes with Coding

Web server controls are created on the server. The runat="server" attribute is added to the control.
The control is processed by the server. Some of the basic web server controls are mentioned
below.
Label control
1. TextBox control
2. ListBox control
3. CheckBox and CheckBoxList control
4. RadioButton and RadioButtonList control
5. DropdownList control
6. Button control
7. ImageButton control
8. Wizard control

1.Label control

The label control is used to show the text in a form. The text cannot be modified by user. The text
is static.

The properties for the label control are:

1. Text: The text for the label is assigned or retrieved


2. Visible: The label control is visible to the user
Syntax for label control:
Code:
<asp:Label ID="label1" runat="server" Text="Name" />

2. TextBox control

The data is retrieved from the user through the textbox control. The textbox control is single line,
multi line or password. In single line textbox, characters are added to single line. For multi line,
multiple lines are displayed. The characters are masked in the password.
The properties for the textbox control are:

1. Text: The text in the textbox control is accessed or assigned


2. Rows: The vertical size of the textbox control is assigned
3. Height: The height of the control is assigned
4. MaxLength: The maximum number of character is entered in the control.
Syntax for textbox control:
Code:
<asp:TextBox ID="Text1" runat="server" ></asp:TextBox>

3. ListBox control

The collection of list items is defined in the listbox control. More than one item can be selected
using the control.

1. Rows: The vertical size of the listbox control is set. If there are more times, a scroll bar is
added to it.
2. Items: The collection of list items is represented in the control
3. SelectionMode: The number of items selected by the user is set. The property can have
value as Single or Multiple.
4. SelectedValue: The value of the item currently selected by the user. The value is
dependent on one or more items selected.

1|Page
4. CheckBox and CheckBoxList control

The individual choices are provided to the user through the checkbox control. A single checkbox is
added to the web form. The checkboxlist contains collection of checkboxes. The list is useful when
the user needs to add a series of checkboxes to the page.

Syntax for CheckBox control:

Code:
<asp:CheckBox ID="CheckBox1" runat="server"></asp:CheckBox>

Syntax for CheckboxList control:

Code:
<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged" >
</asp:CheckBoxList>

Properties of the checkbox control are:

1. Text: The text for the checkbox control is added.


2. Items: The individual check boxes are added to the control.
3. TextAlign: The alignment of the Text property of the control
4. RepeatDirection: The direction to which the control must be repeated is defined
5. RepeatColumns: The number of columns used for repeating the values

5. RadioButton and RadioButtonList control

The radiobutton control provides set of choices. The control can be added to the web form. A
single radio button is added in the radiobutton control. A collection of radio buttons is added to the
radiobuttonlist.

Syntax for RadioButton control:


Code:
<asp:RadioButton ID="Radio1" runat="server" ></asp:RadioButton>

Syntax for RadioButtonList control:


Code:
<asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="RadioButton1_SelectedIndexChanged" >
</asp:RadioButtonList>

Properties of RadioButtonList control:

1. Text: The text for the radiobutton control is added.


2. TextAlign: The alignment of the Text property of the control
3. Items: The individual radio buttons are added to the control.
4. RepeatColumns: The number of columns used for repeating the values

6. DropdownList control

The control allows user to select the values from some predefined items. An item is a separate
object containing the properties. User can add items through the Items property. Only one item
can be selected at a time.

Syntax for dropdown list control is:


Code:
<asp:DropDownList ID="Drop1" runat="server">
<Items>
</Items>
</asp:DropDownList>
2|Page
The properties used in the drop down list control are:
1. Items: The collection of items present in the drop down list
2. Width: The width of the control is set.
3. Height: The vertical size of the control is set

7. Button control

The control is used for posting the data from the user to the web applications. The page is posted
to the server, the click event is triggered. Three types of button as LinkButton, ImageButton and
Button are provided by ASP.NET.

1. ImageButton: It is added in the form of a graphic button. A good look of the button appears
to the user.
2. LinkButton: It is used as a hyperlink on the web page. The client side script is used for
performing the postback to the server.
3. Button: The general button used for rendering the HTML input element.

8 ImageButton control

An imagebutton is used for displaying an image. All the image control properties are inherited
using the ImageButton control.
Properties of ImageButton control:
1. ImageAlign: User for aligning the image on the page. The values can be top, left, right,
bottom, etc.
2. ImageURL: The URL of the image is shown
3. CommandName: The command name associated with the control is displayed.
4. AlternativeText: The text to be displayed when the web browser does not support the
images.
5. CommandArgument: The event associated with the command name.

9. Wizard Control
The wizard contains group of forms for performing the specific task. It performs step by step task
for collecting user related information. It provides user with built in steps, add new steps and
modify the order of the steps.
User can navigate between the steps provided by the wizard. The data across the pages is
maintained in the state while performing the wizard steps.
Properties of the wizard control are:

1. ID: It states the unique identifier associated with the control


2. Enabled: The value stating the wizard content is enabled.
3. ToolTip: The text to be shown when the mouse hovers over the control
4. WizardSteps: A collection of all the WizardStepBase objects used for defining the control

3|Page
Validators
There are various validation controls provided by ASP.NET. They are added to the controls for
validating the input values added by the user.

 Range Validator
 RequiredField Validator
 Regular expression validator
 Compare validator
 Custom validator
 Validation summary

BaseValidator class

The validator consists of the properties inherited from the BaseValidator class. The properties and
methods used by the validation controls are as listed below.

1. Display: The error message used for the specific value is shown
2. ControlToValidate: The control to be validated is assigned by the user
3. ErrorMessage: The error value shown when the validation is performed
4. EnableClientScript: The client side validation is initiated
5. Validate(): The control is validated and the IsValid property is validated

Range Validator

The range validator is used for checking the values defined in a specific range.

Properties of the range validator are:

1. BackColor: The background color of the web server control is assigned.


2. BindingContainer: The data binding of the control is defined
3. Context: The HttpContext object associated with the server control is defined
4. Display: The error message to be shown when the validation control is stated
5. EnableTheming: The value used for showing the themes applied to the control
6. ID: The identifier assigned to the server control
7. MinimumValue: The minimum value of the validation is assigned
8. MaximumValue: The maximum value of the validation is assigned
9. Style: The text attributes which are rendered as the style attributes are defined
Some of the methods of Range Validator.

1. AddedControl: Once the child control is added to the collection, it is called by the user
2. ApplyStyle: The non empty elements are applied a specific style to the control
3. ClearChildState: The view state and control state information for the controls is removed
4. DataBind: Used for binding the data source to the server control and child controls
5. Finalize: The resources are removed from the system and are garbage collected
6. HasControls: If there are child controls present in the server controls
7. OnLoad: The Load event is raised by the user
Syntax of range validator:
Code:
<asp:RangeValidator ID="rg1" runat="server" ControlToValidate="TextBox1" MinumumValue="10"
MaximumValue="50" ErrorMessage="Values not in range" Type="Integer" >
</asp:RangeValidator>

4|Page
RequiredField Validator

The required field validator is used to check that the field contains value.

Some of the properties of the required field validator are:

1. Attributes: The collection of the attributes not corresponding to the properties is shown.
2. ClientID: The control ID for the HTML markup created by ASP.NET
3. ControlToValidate: The input control to be validated by the user
4. Display: The behavior of the error message in the validation control is shown.
5. ErrorMessage: The error message for the control when it fails validation
6. ID: The unique identifier for the control is defined
7. Width: The width of the control can be assigned
Some of the methods of the required field validator are

1. AddedControl: It is called when the child control is added to the collection


2. ApplyStyle: The non empty elements stated by the style of the control are copied.
3. ClearChildControlState: The control state information is deleted from the server child
controls
4. Focus: Provides the focus to the control
5. HasEvents: The value stating the events registered for the controls and the corresponding
child controls
6. SaveViewState: The state is saved which is modified after the method was invoked
7. ToString: The string stating the current object is returned
8. Validate: The validation with the corresponding control is performed
Syntax of RequiredField Validator:

Code:
<asp:RequiredFieldValidator ID="field1" runat="server" ControlToValidate="textbox1"
ErrorMessage="Value must be added"></asp:RequiredFieldValidator>

Regular expression validator

The validator is used for validating the value present in the control is similar to the expression
defined.

Some of the properties of RegularExpressionValidator are:

1. AccessKey: Provides the access key used for navigating the server control
2. Context: The HttpContext object associated with the control is retrieved
3. CssClass: The CSS class is rendered through the web server control
4. Display: The display of the error message in the validation control is defined
5. Events: The list of event handler used as delegates for the control
6. ID: The identifier associated with the specific server control is defined
7. SkinID: The skin to be added to the control is defined
8. TemplateControl: The reference of the template is defined
Some of the methods of the RegularExpressionValidator are:

1. BuildProfileTree: The information about the server control is collected and provided as an
input to the Trace property
2. ClearChildControlState: User for removing all the information of view and control state for
all the server controls

5|Page
3. EndRenderTracing: The design time rendering of the data is ended
4. Finalize: The object is allowed to free the resources and the cleanup operations are
performed
5. GetType: The Type of the current instance is provided
6. OnBubbleEvent: It checks if the server control is passed to the page UI server control
structure
7. ResolveUrl: The URL is converted to the usable one by the client
8. SetDesignModeState: The design time data for the control is set
Syntax for RegularExpression validator is:
Code:
<asp:RegularExpressionValidator ID="reg1" runat="server" ControlToValidate="Control1"
ErrorMessage="Show the string" ValidationExpression="string" >
</asp:RegularExpression>

Compare validator

It is used for comparing the values added by the user in the input control or with a constant value
defined by the user.

Properties of Compare validator:

1. BindingContainer: It provides the control consisting of the data binding


2. BorderWidth: The border of the control can be modified
3. ControlStyle: The style of the web server control is defined
4. Enabled: The value stating the validation control is enabled or not
5. Events: The list of event handler delegate to the control are provided
6. Operator: The operator used for the comparison is defined
7. TemplateControl: The reference of the template of the control is provided
8. ValueToCompare: It accesses or assigns the value which is compared by the user value
Methods of Compare Validator:

1. AddAtttributesToRender: The attributes of the control are added to the output stream.
2. BeginRenderTracing: The design time rendering of the data is performed
3. EndRenderTracing: The design time rendering is stopped by the user
4. GetControlRenderID: The clientID for the control is retrieved
5. IsLiteralContent: It checks whether the server control contains literal content
6. OpenFile: The stream used for reading the file
Syntax for Compare Validator:

Code:
<asp:CompareValidator ID="Compare1" runat="server" ControlToValidate="control1"
ControlToCompare="control2" ErrorMessage="Values must match" Operator="Equals">
</asp:CompareValidator>

Custom validator

The user defined validations are performed on the user control. The client and server side
validation are used. The ClientValidationFunction property is used to perform the client side
validation. The ServerValidate event is used for validating the server side.

Properties of custom validator:

1. Adapter: The browser related adapter for the control is defined


2. ControlStyle: The style for the web server control is defined
3. ControlToValidate: The control validated for the user inputs

6|Page
4. DesignMode: The value stating the control used in the design surface
5. IdSeperator: The character used to change the identifiers
6. Parent: The reference to the server control is defined
Methods of custom validator:

1. AddParsedSubObject: The notification for every element parsed and added


2. ClearChildState: The view state and control state for the servers child controls is defined
3. ControlPropertiesValid: It checks whether the control contains valid values
4. DetermineRenderUplevel: It decides whether the validation control can perform client side
validation
5. GetHashCode: The hash function for the control is retrieved
6. RemovedControl: Once the child control is removed, it is called by the user
7. SaveControlState: The server control state changed are modified by the user
Syntax for custom validator control is:

Code:
<asp:CustomValidator ID="custom1" runat="server" ClientValidationFunction="function1"
ErrorMessage="CustomValidator values" >
</asp:CustomValidator>

Validation summary

The Validation summary control is used for displaying the error messages present on the web
page. The ErrorMessage property is used for showing the values when the validation is not
performed.
Syntax for Validation summary:

Code:
<asp:ValidationSummary ID="validation1" runat="server" DisplayMode="BulletList"
ShowSummary="false" >
</asp:ValidationSummary>

Example to demonstrate the validation controls in an ASP.NET application

1. Open Visual Studio application in your system. Create a web application


2. In the source view, add the following code.
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
<div>
<table style="width:77%";>
<tr>
<td colspan="3" align="center">
<asp:Label ID="lbl1" runat="server" Text="Student admission form" >
</asp:Label>
</td>
</tr>
<tr>
<td>
StudName:
</td>
<td>
<asp:TextBox ID="Text1" runat="server"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="req1" runat="server" ControlToValidate="Text1"
ErrorMessage="Value must be added" >
7|Page
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
StudAge:
</td>
<td>
<asp:TextBox ID="text2" runat="server"></asp:TextBox>
</td>
<td>
<asp:RangeValidator ID="range1" runat="server" MaximumValue="50"
MinimumValue="20" ControlToValidate="text2" ErrorMessage="Values not in range" >
</asp:RangeValidator>
</td>
</tr>
<tr>
<td>
Email:
</td>
<td>
<asp:TextBox ID="text3" runat="server"></asp:TextBox>
</td>
<td>
<asp:RegularExpressionValidator="reg1" runat="server" ControlToValidate="text3"
ErrorMessage="Email not in proper format" ValidationExpression="\w+([-+.’)\w+)*@\w+([-
.]\w+)*\.\w+([-.])\w+)*" >
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btn1" runat="server" Text="Show" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="valid1" runat="server" DisplayMode="BulletList"
ShowSummary="true" />
</div>
</form>
</body>
3. When the code is compiled and executed, the following result is displayed.

8|Page
Control State

The control state data is used for monitoring the control order is working effectively. The
ControlState property is used to persist the information specific to the control.

Application State
The HttpApplication class is used for providing the application state information. The application
specific values can be saved in the application state and are managed by the server. The state is
a global storage and can be accessed through the pages in the application.

The data is present in key/value dictionary for the specific URL.

Properties of HttpApplication state are as mentioned below.

1. Count: The number of objects in the HttpApplication class


2. AllKeys: The access keys are retrieved using the collection
3. StaticObjects: The objects present in the <object> tag are accessed
4. Item[Int32]: The single HttpApplicationState object is retrieved by the index
5. Contents: The reference for the HttpApplicationState object
Methods of HttpApplication state are listed below.

1. Clear: All the objects are removed from the collection


2. Add: A new object is added to the collection
3. GetType: The Type of the current instance is accessed
4. Remove: The named objects are removed from the collection
5. Set: The value of an object is updated
6. Lock: The variable is accessed for managing the synchronization
7. GetHashCode: The default hash function is accessed
The application state data are maintained using the events stated below.

1. Application_Start: It states the start of the applciation


2. Application_End: The end of the application is determined
3. Application_Error: The error present in the application is mentioned
4. Session_Start: The start of the session is specified
5. Session_End: The end of the session is specified
Advantages of the Application State

1. The application state is accessed through all the web pages. A single copy can be used for
storing the information
2. It is easy for users and provides consistent framework classes.
Disadvantages of the Application State

1. The server memory is needed by the application state. The server performance is affected.
2. Once the server process is destroyed, the global data of the application state is removed.
3. The unique values cannot be saved in the application state
There are three events provided by ASP.NET application. They are as listed below.

1. Application_Start: It is raised when the application starts the execution. The application
variables can be initialized.
2. Application_End: When the application closes, the event is raised. All the application
resources for the user are released.
3. Application_Error: When unhandled errors occur, the exception is raised.
Directives
9|Page
The syntax for directives in ASP.NET is:

Code:
<%@ directive_name attribute = value [ attribute = value ] %>

Every directive consist of attribute- value pair. There are various application directives supported
in ASP.NET. The other directives used with the ASP.NET files are:

1. @Import: It is used for importing the namespace in an application.


2. @Assembly: The assembly is linked to the application at the parse time.
In this tutorial, let’s explore all the directives used in ASP.NET.

Application Directive

The attributes specific to an application are defined using the application directive. They are
present in the .aspx files.

Syntax for application directive:


Code:
<%@ Application attribute="value" [ attribute = "value" ] %>

The various attributes used by the application are:

1. Language: The code blocks are used inside the language


2. Inherits: The class name from where the code is inherited
3. Description: The explanation of the application. They are not processed by the parsers and
compilers.
4. CodeBehind: The source code file containing the application class is defined.
5. Language: The language used for compiling the application is defined.
Example:
Code:
<%@ Application Inherits="MyApp1.object" Description="New App" %>

Control Directive
It is used for defining the user specific controls used by the compiler and parser.
Syntax for control directive:
Code:
<%@ Control attribute="value" [ attribute = "value" ] %>

Some of the attributes used by the control directive are:


1. ClassName: The name of the file used in the control
2. AutoEventWireup: It states the Boolean value used for enabling and disabling the event
handlers
3. Description: It states the description of the control page, ignored by the compiler
4. Inherits: The class from where the control page is inherited
5. Explicit: The option explicit mode is used by the user.
6. EnableViewState: It is the Boolean value indicating the view state is maintained across
page requests.
7. Strict: The compiler is advised with the strict mode.
8. Language: The code and script language is defined
9. CodeFileBaseClass: The path of the base class and the corresponding code behind class is
defined.
10. EnableTheming: The themes used on the control are defined. It is represented by a
Boolean value.
11. Src: The path to the source file consisting of the code to be linked to the control.
12. TargetSchema: The name of the schema used for validating the control is defined.
10 | P a g e
Example:
Code:

<%@ Control Language="C#" EnableViewState="false" %>

Assembly Directive
The assembly directive is used for linking the application file. The files can be user control, web
pages, or a application file. All the assembly classes and interfaces are present.
The syntax for the assembly directive is:
Code:
<%@ Assembly Name="assembly1" %>
<%@ Assembly Src="pathname" %>
The attributes of the assembly directive are:

1. Src: The path for the source code files to be linked dynamically
2. Name: The assembly name to be linked.
Example:
Code:
<%@ Assembly Name=AssemblyNew" %>
<%@ Assembly Src="Demo.cs" %>

Import Directive

The namespace is imported to the web page using the import directive. The directive specified in
the global.aspx file is assigned to the complete application. If it is specified to the specific page, it
is applied to that control or page.

The syntax for import directive is:

Code:
<%@ Import Namespace="value" %>

The attribute used in the Import directive:

1. namespace: The fully qualified name of the imported namespace.


Example:

Code:
<%@ Import Namespace="System.Net" %>

Implements Directive

The implements directive states that the page, user control or master page is implemented in
specified .NET framework.

The syntax for implements directive is:

Code:
<%@ Implements interface ="interface_name" %>

Attributes associated with the implements directive:

1. interface: The interface implemented on the page or user control.

MasterType Directive
The directive assigns the class name to the Master property of a page. The page is made strongly
typed.

11 | P a g e
The syntax for the MasterType directive is:

Code:
<%@ MasterType attribute="value" [ attribute = "value" ] %>

Attributes associated with the MasterType directive are:

1. TypeName: States the name for the master page


2. VirtualPath: The path assigned to the file creating a strong type

Master Directive
The directive is used to specify the page file as master file.

The syntax for the master directive is:

Code:
<%@ MasterPage Language = "C#" AutoEventWireUp="true" CodeFile="SiteMaster.master.cs"
Inherits="SiteMaster" %>

Attributes associated with the Master directive are:

1. ClassName: The name of the class associated with the control.


2. CodeFile: The file containing the separate partial class and event handlers associated with
it.
3. AutoEventWireup: The simple event handlers used for specifying the life cycle of a web
page.
4. Debug: States to compile the master page using the debug symbols.
5. EnableTheming: It shows the look of the master page and controls of the master page
6. Description: A text description is provided to the user.
7. Explicit: The page is compiled using the Option Explicit mode. The value true states that the
compile is enabled.
8. Language: The language used for the inline rendering. Code declaration blocks within the
page.
9. MasterPageFile: The .master file states the master page.
10. Strict: The page is compiled using the Option Strict mode.
11. Src: The source file name is defined in the code behind class.
Example:

Code:
<%@ Master Language="C#" CodeFile="Master1.master.cs" Inherits="MasterPage" %>

Page Directive

The page directive defines the attributes for the specific page for the compiler or parser.

Syntax for page directive:

Code:
<%@ Page attribute="value" [ attribute="value" …. ] %>

The attributes of the page directive are:

1. Buffer: It is a Boolean value stating the enabling and disabling of the HTTP response
buffering.
2. ClassName: It is the name of the class for the page.
3. AutoEventWireup: It states that the page is automatically bound to the methods. Indicated
by a Boolean value.
12 | P a g e
4. CodeFile: The code behind file name
5. ClientTarget: The browser where the controls are rendered by the user.
6. Description: The text value described for the particular page. The parser does not pass the
values
7. EnableViewState: The value used for stating the enabled or disabled condition of the view
state
8. Error Page: The redirection of the URL if an unhandled exception occurs
9. Language: The programming language for the code to be added
10. TraceMode: It is used for enabling or disabling the tracing values.
11. ValidateRequest: The value stating the input data is validated across all the listed values.
12. Transaction: The transaction supported by the browser is defined.
Example:
Code:
<%@Page Language="C#" EnableViewState="True" Description="Web Page" %>

OutputCache Directive

The directive controls the output caching capacity of the web page or the control.
Syntax for OutputCache directive:

Code:
<%@ OutputCache Duration="Seconds"
Shared="True | False"
VarByControl = "controlname"
VarByHeader="header"
VarByParam = "parameter"
CacheProfile="profile name"
ProviderName="provider name"
Location=" Client | Server | None | ServerAndClient | Any "
%>

Attributes used in the OutputCache directive are:

1. Duration: The time used by the page is cached. It is defined in seconds.


2. VarByHeader: The list of the HTTP headers used by the output cache.
3. VarByParam: The list used for modifying the output cache.
4. VarByCustom: The custom cache output requirements are stated.
Example:

Code:
<%@ OutputCache Duration="50" VarByParam="None" %>

Reference: Directive

The reference directive is used for showing that another page or control is compiled to the current
page.

Syntax for reference directive:

Code:
<%@ Reference Page="Default.aspx" %>

Attributes of the Reference directive are:

1. Page: The external page that needs to be dynamically linked to the current file.
2. virtualpath: It states the reference of the file.
3. Control: The user control used for compiling and linking to the current file.

Register Directive

13 | P a g e
It is used for referring the custom control to the tag prefix created by the user.
The syntax for the Register directive is:
Code:
<%@ Register tagprefix="tag1"
namespace="namespace"
assembly="assembly" %>

<%@ Register tagprefix="tag2"


tagname="tagname"
src="pathname" %>

Attributes for the Register directive are:

1. assembly: The assembly where the namespace is associated with the tagprefix attribute.
2. src: The location where the user controls file is associated with the tagprefix:: tagname
combination.
3. tagname: The alias associated with the class.
4. tagprefix: The alias providing the shorthand reference to the namespace of the file.

14 | P a g e
Rich Control
Rich controls in ASP.NET provide additional functionality for creating rich applications. In this
article, we shall explore the following controls.
AdRotator control
The AdRotator control selects from the banner advertisements. They are added in an XML file.
The file is known as advertisement file. The control states the file and the window used for linking
the file.

Syntax for AdRotator control:

Code:
<asp:AdRotator AdvertismentFile="file1.xml" runat="server" Target="_top" />

The advertisement file consist information about the advertisements to be displayed. The data is
saved in a structured format through the formatted tags.

Consider a code snippet demonstrating the XML file.

Code:

<STUDENT>
<STUDNAME>John</STUDNAME>
<CLASS>12</CLASS>
<MARKS>50</MARKS>
</STUDENT>

The elements used in the advertisement file are mentioned below.

1. Ad: A unique Ad element is added to the file


2. Advertisements: The advertisement file is present in this tag
3. NavigateUrl: The link user follows when the ad is clicked
4. ImageUrl: The image path is shown to the user
5. AlternateText: The text is shown when the picture is not visible
6. Impressions: The number of occurrences of the ad is defined
7. Width: The width of the image is defined
8. Height: The height of the image is defined
9. Keyword: The group of advertisements is defined
Properties of the AdRotator control are:

1. DataMember: The name of the list of data specified by the user used for binding in absence
of the advertisement file.
2. AdvertisementFile: The path for the advertisement file is defined
3. DataSource: The control where the data is accessed
4. AlternateTextField: The field name where the alternate text is provided
5. Font: The font associated with the banner control is defined
6. Target: The window used for displaying the content of the page
7. NavigateUrlField: The name of the field where the URL for navigation is defined
Events of the AdRotator control are:

1. DataBinding: The server control is used for binding with the data source
2. AdCreated: The event is raised when the trip to the server is done, the page is rendered
later.
3. Init: The server control is initialized during the page life cycle
4. Load: The server control is loaded to the Page
5. Unload: The server control is unloaded from the memory

15 | P a g e
Consider an example to demonstrate the use of AdRotator control.

1. Create an ASP.NET web application using the Visual Studio application.


2. Add an XML file to the application and type the following code.
Code:
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>Koala.jpg</ImageUrl>
<NavigateUrl>http://www.msdn.com</NavigateUrl>
</Ad>
<Ad>
<ImageUrl>Chrysanthemum.jpg</ImageUrl>
<NavigateUrl>http://www.google.com</NavigateUrl>
</Ad>
</Advertisements>

3. In the source code page of the application, add the following code.
Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:AdRotator ID="Ad1" runat="server" AdvertisementFile="~/XMLFile.xml" />
</div>
</form>
</body>
</html>

4. The following output is displayed when the code is executed.

https://www.dropbox.com/sh/kxvy0jkhkdrlq6l/AADFbsrjwDIIcozD9FVMser0a?dl=0

MultiView control

The list of View controls forms the multiview control. Every page consists of view control which is
used for group management. Only one view is displayed to the user.

Syntax for MultiView control

Code:
<asp:MultiView ID="MultView1" runat="server">
<asp:View ID="view1" runat="server"></asp:View>
</asp:MultiView>

Properties of multiview control:

1. ID: The unique identifier used for identifying the control on the web page

16 | P a g e
2. Views: The group of view controls in a multiview control
3. ActiveViewIndex: It is zero based index used for representing the active view.
Methods of multiview control:

1. GetActiveView: The active view is accessed by the user


2. SetActiveView: The active view is assigned by the user
Events of multiview control:

1. Activate: It is raised by the active view


2. Deactivate: Used by an inactive view
3. ActiveViewChanged: When the view is modified by the user, it is raised
Consider the following example to demonstrate the MultiView control.

1. Create an ASP.NET web application and open the source window


2. Add the following code in the source view.
Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:MultiView ID="Multi1" runat="server" ActiveViewIndex="1">
<asp:View ID="view1" runat="server">
<br/>
<asp:Label ID="Label1" runat="server" Text="Show values" >
</asp:Label>
</asp:View>

<asp:View ID="view2" runat="server">


<asp:Label ID="label2" runat="server" Text="Welcome to View2" >
</asp:Label>

<asp:BulletedList ID="bullet" runat="server">


<asp:ListItem>C#</asp:ListItem>
<asp:ListItem>ASP.NET</asp:ListItem>
<asp:ListItem>Java</asp:ListItem>
</asp:BulletedList>
</asp:View>

</asp:MultiView>
</div>
</form>
</body>
</html>

Panel control

The panel control acts storage for all the controls used in the page. The appearance for the
controls is managed.

Syntax for Panel control

Code:

<asp:Panel ID="Panel1" runat="server">


<asp:Panel>

Properties of Panel control:

17 | P a g e
1. Direction: The text direction of the control in the panel is defined
2. BackImageUrl: The background image of the post is stated
3. GroupingText: The grouping of the text as a field is defined
4. Wrap: The text wrapping is performed
5. ScrollBars: The scrollbars are assigned within the panel
The following example demonstrates the use of panel control in ASP.NET.

Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="panel1" runat="server" BackImageUrl="~/Chrysanthemum.jpg"
ScrollBars="Both" Wrap="true" Width="400px" Height="400px" >
<table>
<tr>
<td colspan="2">
</td>
</tr>

<tr>
<td>EmpName</td>
<td>
<asp:TextBox ID="text1" runat="server"></asp:TextBox>
</td>
</tr>

<tr>
<td>EmpAge</td>
<td>
<asp:TextBox ID="text2" runat="server"></asp:TextBox>
</td>
</tr>

<tr>

<td>
<asp:Button ID="btn1" runat="server" Text="show" />
</td>
</tr>
</table>
</asp:Panel>
</div>
</form>
</body>
</html>

The output for the above code is:

18 | P a g e
Calendar control

Calendar control is used for providing a month display to the user. User can view week, month,
days of the week, dates, etc.

Syntax for Calendar control


Code:
<asp:Calendar ID="calendar1" runat="server">
</asp:Calendar>

Properties of the calendar control

1. CellPadding: The space between the data and the border of the cell is defined
2. Caption: The caption for the control is defined
3. DayHeaderStyle: The day of the week is displayed using the style properties
4. FirstDayOfWeek: The day of the week is displayed
5. PreMonthText: The text for the previous month navigation control
6. SelectedDates: The collection of DateTime objects for the selected dates
7. SelectMonthText: The text for month element from the selector column
8. TitleFormat: The format for the title section is defined
9. VisibleDate: The date for the month to be displayed is defined
10. TodaysDate: The value for todays date is defined
Events for Calendar control

1. DayRender: When the data cell of the control is rendered


2. SelectionChanged: When user selects from the calendar, the event is raised
Consider the following example to demonstrate the calendar control.

Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Calendar ID="calendar1" runat="server" BackColor="Aqua"
BorderColor="Black" DayStyle-Font-Bold="true" TodayDayStyle-Font-Bold="true"
onselectionchanged="calendar1_SelectionChanged">
</asp:Calendar>
</div>
</form>
</body>
</html>

Add the following code in the code behind file.

Code:

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


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

protected void calendar1_SelectionChanged(object sender, EventArgs e)


{
string date=" ";
date = "Selected Date "+ calendar1.SelectedDate.ToString();
19 | P a g e
}
}

The output for the code is:

20 | P a g e
Managing States
To overcome this situation, there are several options added at page and application levels. In this
article, we shall explore various concepts related to state management.

Introduction to different states in ASP.NET

There are four states used for managing states in ASP.NET application. They are as listed below:

 View State
 Session State
 Control State
 Application State

View State

View state in ASP.NET provides information for the particular ASP.NET page. If there is a
requirement for maintaining the web page, the .NET framework manages it automatically.
The information about the view state is serialized into XML and encoded through base. The page
performance varies if the data is large. Although the view state is enabled some of the controls do
not need it. The view state can be disabled for a particular control.
The view state for the control can be disabled by modifying the EnableViewState attribute to false.
The view state for a web page can be modified by changing the EnableViewState attribute in the
@Page directive.
The view state for the complete application can be modified through the <pages> section in config
file.

Advantages of view state

1. The view state values can be encoded, hashed and compressed. As a result the values are
secured.
2. There is no need to implement code for maintaining view state.
3. There is no server resource used for managing the state
Disadvantages of view state

1. The data stored for view state is saved into more hidden fields on the web page. The data
can be modified by the users.
2. The performance for the web page is reduced as the values are saved in the page itself.
3. The data storage is restricted for the memory of the device used.
Consider the following example to demonstrate the view state in ASP.NET

1. Add the following code in the source page of application.


Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
EmpName:<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
<asp:Button ID="btn1" runat="server" Text="Show" onclick="btn1_Click" />
<asp:Button ID="btn2" runat="server" Text="Submit" />
<br/>
Value from Viewstate is: <asp:Label ID="lbl1" runat="server"></asp:Label>
</div>
</form>
</body>
21 | P a g e
</html>

2. The following code is added in the code behind file.


Code:

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


{
protected void Page_Load(object sender, EventArgs e)
{
if(ViewState["EmpName"] ! = null)
{
lbl1.Text= ViewState["EmpName"].ToString();
}
else
{
lbl1.Text = "Value not available";
}
}
protected void btn1_Click(object sender, EventArgs e)
{
ViewState["EmpName"] = txt1.Text;
lbl1.Text = txt1.Text;
}
}

3. The code is compiled and executed and the following output is displayed.

Session State

The session state in ASP.NET helps user to save values. The scope of the state is restricted to
current browser. Every user has a unique session id. The key/value pair structure is used for
saving them.

The SessionStateItemCollection object is used for storing the session variables. The Session
property is used for exposing the object. The variables are indexed by variable name or integer
index.

Properties of HttpSessionState class are as listed below.

1. Count: The number of items present in the session state collection


2. CookieMode: The application is configured for the cookieless sessions
3. IsReadOnly: State whether the session is read only
4. Keys: The collection of keys for the values present in the session collection
5. Timeout: The time in minutes used by the provider for ending the session
Methods of the HttpSessionState class are listed below.

1. Add: The new item is added to the collection


2. Clear: All the key and values are removed from the collection
3. GetType: The Type of the current instance is obtained
4. RemoveAll: The key and values from the collection are removed
22 | P a g e
5. ToString: The string representing the current object is removed
Advantages of the Session State

1. The events can be raised and used by the application


2. It is consistent with the .NET framework and easy to use
3. Customized session state can be used through the state provider
4. The contents are kept in session state variables using the IIS.
5. The session management events can be created by own application
Disadvantage of the Session State

The state variables are present in the memory till they are removed or replaced. The server
performance is degraded.

Consider the following example to demonstrate the use of session state

1. Add the code in the source page of the application


Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="label1" runat="server"></asp:Label>
<br></br>
<asp:Label ID="label2" runat="server"></asp:Label>
<asp:TextBox ID="text1" runat="server"></asp:TextBox>
<br/>
<asp:Button ID="btn1" runat="server" Text="Save" onclick="btn1_Click" />
<br/>
<asp:HyperLink ID="hyp1" runat="server" Text="Navigate to Session"
NavigateUrl="~/Default2.aspx"></asp:HyperLink>
</div>
</form>
</body>
</html>

2. Add the following code in the code behind file.


Code:

protected void btn1_Click(object sender, EventArgs e)


{
Session["UserName"] = text1.Text.ToString();
label1.Text = "Session saved";
}

3. Add another web page in the application. The following code is added in the source page.
Code:

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

23 | P a g e
<asp:Label ID="label1" runat="server"><asp:Label>
<br/>
<asp:HyperLink ID="hyper1" runat="server" Text="GoTo Page1"
NavigateUrl="~/Default.aspx"></asp:HyperLink>
</div>
</form>
</body>
</html>

4. In the code behind file, add the following code.


Code:
using System;
using System.Collection.Generic;
using System.Linq;
using System.Web;

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


{
protected void Page_Load(object sender, EventArgs e)
{
label1.Text = "Welcome" + Session["UserName"];
}
}

5. When the code is compiled and executed, the following output is displayed.

https://www.go4expert.com/articles/managing-aspnet-t34148/
Basic Controls

24 | P a g e

Das könnte Ihnen auch gefallen