Professional Documents
Culture Documents
unit2
unit2
unit2
Page 1
Unit:2 Server Control
2.1IsPostBack in asp.net:
IsPostBack is a Page level property, that can be used to determine whether the page is
being loaded in response to a client postback, or if it is being loaded and accessed for the
first time.
The Page.IsPostBack property is a boolean property that indicates whether the page is
being rendered for the first time or is being loaded in response to a postback. A postback is
a request sent from a client to the server from the same page, user is already working with.
The Page.IsPostBack property can be used to check the value of this property and
perform different actions depending on whether the page is loading for the first time or
not. For example, you can use this property to avoid re-binding data to a control if the page
is not on its initial load.
2.2 DataBinding:
2.2.1 Grid View:
What is GridView in C#?
Data can be displayed in a tabular manner with sorting, paging, and editing options using
the C# data presentation control GridView. The namespace Web.UI.WebControls is
frequently used in web applications. GridView can be bound to various data sources like
databases, XML, and other data sources.
GridView in C# has several properties that can be used to customize its appearance and
behavior. Some of the key properties of GridView are:
Page 2
Unit:2 Server Control
o AllowSorting:This property allows you to enable or disable data sorting in the GridView.
o ShowHeader:This property allows you to show or hide the header of the GridView.
o ShowFooter:This property allows you to show or hide the footer of the GridView.
o EditIndex:This property allows you to set the index of the row being edited in
the GridView.
Using GridView in C# is easy and straightforward. The first thing to do is to give your web
form a GridView control. We can implement it by dragging and dropping the control from
the toolbox onto your form.
Next, you need to bind the GridView control to your data source. Setting the data source as
the GridView control's DataSource attribute will do this. If you wish to automatically
create columns based on the data source, you can also set the AutoGenerateColumns
attribute to true.
Once you have bound the GridView control to your data source, you can customize its
appearance and behavior by setting various properties like AllowSorting, AllowPaging,
and EditIndex.
Moreover, GridView has a number of events that you can utilize to modify its behavior.
Some of the key events of GridView are:
o RowDataBound:This event is fired when a row is bound to the GridView. This event
allows you to change how the row looks.
o RowEditing:This event is triggered whenever a row in the GridView is edited. This event
can be used to validate data or execute other actions on the row.
o RowDeleting:This event is triggered whenever a row in the GridView is deleted. You can
use this event to confirm the deletion or perform any other operation before deleting the
row.
o PageIndexChanged:This event is fired when the user changes the page in the GridView.
You can use this event to rebind the GridView with the new data.
The ListView Controls are used to display a collection of items. It uses one of the view lists,
such as LargeIcon, SmallIcon, Details, List, and Tile. Furthermore, the ListView allows the
user to add or remove icons from the ListView Control.
Page 3
Unit:2 Server Control
Properties Description
Alignment The Alignment property is used to set the alignment for the item
in the ListvVew Control.
Activation The Activation property is used to get or set a user-requested
action to activate an item.
CheckBoxes The CheckBoxes property sets a value to display the checkbox
that appears next to each item in the list view control.
Columns The Columns property is used to display the collection of
columns header in the ListView Control.
CheckIndices The CheckIndices property is used to get all checked items in the
ListView Control.
GridLines The GridLines Property is used to display the gridlines between
the rows and columns that contain the items and subitems in the
ListView Control.
Items It is used to collect the collection of the items that are in the
ListView Control.
LargeImageList It is used to set or get ImageList to display it as a large icon in the
ListView Control.
HeaderStyle It is used to set or get the column header style in the ListView
control.
MultiSelect The MultiSelect property is used to set a value that allows
selecting more than items in the ListView control.
SelectedItems It is used to obtain all selected items in the ListView control.
ShowGroups The ShowGroups property set a value that represents whether
the ListView items are displayed in groups.
SmallImageList It is used to set or get ImageList to display the image as a small
icon in the ListView control.
TopItem The TopItem property is used to set or get the first item in
control.
View The View property is used to set the items displayed in the List
view. The View property has the following values:
SmallIcon: It is used to display small size icons.
List: It is used to display items in a list, and it only shows
captions.
LargeIcon: It is used to display large size icons.
Report: It is used to display items and its sub-items.
Page 4
Unit:2 Server Control
Method Description
ArrangeIcons() The ArrangeIcons method is used to arrange all the items
displayed as icons in the ListView control.
FindItemWithText() It is used to search the first ListViewItem that started with the
given text value.
GetItemAt() The GetItemAt method is used to get an item at the specified
location of the ListView control.
Clear() The Clear method is used to clear all the items and columns
from the ListView control.
Sort() The Sort method is used to sort items of the ListView.
Events Description
ItemActivate The ItemActivate event occurred when an item activated in the
ListView control.
ItemChecked The ItemChecked event is found in the ListView control when
the checked state of an item changes.
TextChanged The TextChanged event is found in the ListView control when
the property of the text changes.
ItemCheck When the status of a check item changes, the ItemCheck event
is found in the list view control.
AfterLabelEditEvent It occurs when the user in the ListView control edits the label
for an item.
2.2.3 DataList:
Page 5
Unit:2 Server Control
Itemtemplate: It specifies the Items present in the Datasource, it renders itself in the
browser as many rows present in the data source co collection.
EditItemTemplate: Used to provide edit permissions to the user.
HeaderTemplate: Used to display header text to the data source collection.
FooterTemplate: Used to display footer text to the data source collection.
ItemStyle: Used to apply styles to an ItemTemplate.
EditStyle: Used to apply styles to an EditItemTemplate
HeaderStyle: Used to apply styles to a HeaderTemplate
FooterStyle: Used to apply styles to a FooterTemplate.
2.2.4 DataBindingEvent:
Page 6
Unit:2 Server Control
1.ItemDataBound:
The ItemDataBound Occurs After any control’s object has been created its properties have
been initializied with values retrieved from corresponding data fields.
By accessing the databound item via the event argument’s controlname.item property and
modifying its setting as needed,you can add functionality to your application within an
ItemDataBound event Handler.
2.DataBound:
The DataBound event is fired to indicate that the control’s data binding mechanism has
been completed, After all data items from the chosen data source have been processd,this
event happens.By giving a handler to the DataBound Event, You can additionally
implement Extra logic at this time.
2.2.5 Repeater:
The Repeater control is used to display a repeated list of items that are bound to the
control. The Repeater control may be bound to a database table, an XML file, or another list
of items.
Repeater is a Data Bind Control. Data Bind Controls are container controls. Data Binding is
the process of creating a link between the data source and the presentation UI to display
the data. ASP .Net provides rich and wide variety of controls, which can be bound to the
data.
FooterTemplate: - This template is used for elements that you want to render once after
your ItemTemplate section.
ItemTemplate: This template is used for elements that are rendered once per row of data.
It is used to display records
AlternatingItemTemplate: This template is used for elements that are rendered every
second row of data. This allows you to alternate background colors. It works on even
number of records only.
SeperatorTemplate: It is used for elements to render between each row, such as line
breaks.
Page 7
Unit:2 Server Control
Some point about Repeater Control
It is used to display backend result set. It is used to display multiple tuple.
It is an unformatted control. The Repeater control is a basic templated data-bound list. It
has no built-in layout or styles, so you must explicitly declare all layout, formatting, and
style tags within the control's templates.
The Repeater control is the only Web control that allows you to split markup tags across
the templates. To create a table using templates, include the begin table tag (<table>) in
the HeaderTemplate, a single table row tag (<tr>) in the ItemTemplate, and the end table
tag (</table>) in the FooterTemplate.
The Repeater control has no built-in selection capabilities or editing support. You can use
the ItemCommand event to process control events that are raised from the templates to
the control.
We have to use scriptlets for data access.
Data Bind Control can display connected and disconnected model.
-> DataBind()
-> ItemCreated -> Event
-> DataBound -> Event
System.Commom.Data namespace
-> DBDataRecord Class
2.2.6 FormView:
Page 8
Unit:2 Server Control
ItemTemplate The template that is used to render the record to display only.
Methods of the FormView Control
ChangeMode ReadOnly/Insert/Edit. Change the working mode of the control from
the current to the defined FormViewMode type.
InsertItem Used to insert the record into database. This method must be called
when the DetailsView control is in insert mode.
UpdateItem Used to update the current record into database. This method must
be called when DetailsView control is in edit mode.
DeleteItem Used to delete the current record from database.
1.Label
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 displaya text that does not change, you use the literal text.
Basic syntax for text controls:
<asp:LabelID="lbl"runat="server"></asp:Label>
Properties
Property Description
runat Specifies that the control is a server control. Must be set to"server"
Text The text to display in the label
2.TextBox:
The TextBox control is used to get the input from the user of the webapplication.
An asp.net textbox has several properties, that we need to be aware of as adeveloper.
Properties of a TextBox control
1. TextMode Propertry - SingleLine, MultiLine and Password.
When you set the TextMode to MultiLine, use Rows property to control thenumber of
lines to display for a MultiLine TextBox.
Page 9
Unit:2 Server Control
2. Text - Use this property to set or get the Text from the TextBox.
3. MaxLength - The maximum number of chatacters that a user can enter.
4. ReadOnly - Set this property to true if you don't want the user to change the textin
the TextBox.
5. ToolTip - The tooltip is displayed when the mouse is over the control.
6. Columns - Use this property to specify the width of the TextBox in characters
7. Height - Set the height
8. Width - Set the width
9. AutoPostBack
By default, the TextChanged event of a TextBox control is cached in the viewstate, and is
executed when the webform is submitted thru a postback by clicking the button control.
If you want to change this behaviour, and post the webform immediately when the Text is
changed, set AutoPostBack to true. Setting this property to true, will convert the cached
event into a postback event.
Events of TextBox:
TextChanged - This event is fired, when the text is changed.
Methods of a TextBox:
Focus - Set input focus onto the control.
To view the properties of the TextBox, Right click on the control, and selectProperties.
In the properties window, you can also find the events supported by the control.
All these properties can be set at the design time, or at runtime using code.
3.Button:
The Button is an asp.net web server control. This control is used to performevents. It is also used to
submit client request to the server. To create Button either we can write code or use the drag and
drop facility of visual studio IDE. We can display a simple push button on a web page by adding
button control on asp.net web page.
These entire three buttons has main two events Click and Command events. Bydefault in asp.net
button has click events.
Page 10
Unit:2 Server Control
This is a server side control and asp provides own tag to create it.The example is given below.
<asp:ButtonID="Button1"runat="server"Text="Submit"BorderStyle="Solid"ToolTip="Submit"/> Server
renders it as the HTML control and produces the following code to the browser.
<inputname="Button1"value="Submit"id="Button1"title="Submit"style="border- style:Solid;"
type="submit">
Property Description
4.LinkButton
It is a server web control that acts as a hyperlink. It is used to display a hyperlink-style button
control on the web page. ASP.NET provides a tag to create Link Button and has following syntax. The
Link Button code is like:
<asp:LinkButtonID=”LinkButton1″ runat=”server”>LinkButton</asp:LinkButton>
Property Description
5.ImageButton:
Page 11
Unit:2 Server Control
Use of ImageButton control is to display an image that responds to mouse clicks. Both the Click and
Command events are raised when the ImageButton control is clicked. You can use the OnCommand
event handler to make the ImageButton control behave like a Command button.
This is a server side control and asp provides own tag to create it.
<asp:ImageButtonID=”ImageButton1″runat=”server”/> This
Property Description
6.HyperLink:
The ASP.NET Hyperlink control is used to create a link to another Web page.
Properties:
Text - The link text that will be shown to the user
Navigate URL - The URL of the page to which the user will be sent ImageURL -
The URL of the image, that will be displayed for the link. If you specify both the
Text and ImageUrl, the image will be displayed instead of the
text. If for some reason, the image is not unavailable, the text will be displayed.Target
- If target is not specified, the web page to which the hyperlink is linkedwill be
displayed in the same window. If you set the Target to _blank, the web page will be
opened in a new window.
Methods:
Focus() - Call this method to Set the input focus when the page loads.
Events:
No HyperLink control specific events.
7.DropDownlist:
Page 12
Unit:2 Server Control
The DropDownList control is asp.net web server control. We can use dropdownlist control for hold
group of items. The dropdownlist control is used to store the multiple items and allow user to
select only one item from it.The dropdownlist control is also known as combo box control. In
dropdownlist controlwe canstoremultiple items but wecanselectonlyone itemat atime, that’s whyit is
also known as Single Row Selection Box.
Property Description
SelectedValue Get the value of the Selected item from the dropdown box.
SelectedIndex Gets or Sets the index of the selected item in the dropdown box.
SelectedItem Gets the selected item from the list.
Items Gets the collection of items from the dropdown box.
DataTextField Name of the data source field to supply the text of the items.
DataValueField Name of the data source field to supply the value of the items.
DataSourceID ID of the data source component to provide data.
DataSource The data source that populates the items in the listbox.
AutoPostBack True or false. If true,the form is automatically posted back to the server when
user changes the dropdown list selection. It will also
Fire OnSelectedIndexChanged method.
AppendDataBoundItems true or false. If true, the statically added item (added from .aspx page) is
maintained when adding items dynamically(fromcode behind file)or items are
cleared.
OnSelectedIndexChanged Method name that fires when user changes the selection of the dropdown box.
(Fires only when AutoPostBack=true.)
8.CheckBox:
CheckBox Control is used, when you want the user to select more than oneoption
from the available choices.
For example, the education of a person.
A person can have a graduate degree, post graduate degree and a doctorate.
In this case the user selects all the 3 checkboxes.
Where as a person, may just have a graduate degree, in which case he only
selects, the graduate checkbox.
Page 13
Unit:2 Server Control
Another example, would be when you want the user to select the days of his
availability.
In short, if you want to provide the user with more than one option to select
from, then choose a check box Control.
Important Properties of the CheckBox Control
Checked - This is a boolean property, that is used to check if the check box is
checked or not.
Text - This is a string property used to get or set the text associated with the checkbox
control
TextAlign - right or left. On which side of the check box the text should appear
AutoPostBack - Set this property to true, if you want the webform to be posted
immediately when the checked status of the check box changes.
Methods:
Focus() - Just like TextBox, checkbox also supports, Focus() method. If you want to set
the input focus, to a specific checkbox, Call this method for that check boxcontrol.
Events:
CheckedChanged - This event is fired when the checked status of the check button
control is changed.
Page 14
Unit:2 Server Control
<asp:CheckBox ID="PostGraduateCheckBox" Text="Post Graduate"
runat="server" />
<asp:CheckBox ID="DoctrateCheckBox" Text="Doctrate" runat="server" />
</fieldset>
<br /><br />
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" />
</div>
Code from the CodeBehind file
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PostGraduateCheckBox.Focus();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sbUserChoices = new StringBuilder();if
(GraduateCheckBox.Checked)
{
sbUserChoices.Append(GraduateCheckBox.Text);
}
if (PostGraduateCheckBox.Checked)
{
sbUserChoices.Append(", " + PostGraduateCheckBox.Text);
}
if (DoctrateCheckBox.Checked)
{
sbUserChoices.Append(", " + DoctrateCheckBox.Text);
}
Response.Write("Your Selections: " + sbUserChoices.ToString());
}
protected void GraduateCheckBox_CheckedChanged(object sender, EventArgs e)
{
Response.Write("Graduate Checkbox Selection changed");
}
9.CheckBoxlist:
CheckBoxList control is a single control that groups a collection of checkable list items, Following are some
Page 15
Unit:2 Server Control
important properties that are very useful.
Property Description
SelectedValue Gets the value of first selected item.
SelectedIndex Gets or Sets the index of the first selected item.
SelectedItem Gets the first selected item
TextAlign Gets or Sets the alignment of the check boxtext.
DataTextField Name of the data source field to supply the text of the items.
DataValueField Name of the datasource field to supply the value of the items.
DataSource The data source that populates the items in the checkboxlistbox.
AutoPostBack true/false. If true,the form is automatically posted back to the server when user
click any of the checkbox. It will also fire OnSelectedIndexChanged method.
AppendDataBoundItems true/false. If true,the statically added item(added from.aspxpage) is maintained
when adding items dynamically (from code behind file) or items are cleared.
OnSelectedIndexChanged Method name that fires when user click any of the checkbox in the list.(Fires
only when AutoPostBack=true.)
Items Gets the colleciton of the items from the list.
RepeatLayout table/flow.Gets or Sets the layout of the chekboxes when rendered to the page.
RepeatColumns Gets or Sets the no.of columns to display when the control is rendered.
RepeatDirection Horizontal/Vertical.Gets or Sets the value to indicate whether the control will be
rendered horizontally or vertically.
DataSourceID ID of the datasource component to provide data.
10.Radiobutton:
Radio Button control is used, when you want the user to select only one optionfrom
the available choices.
For example, the gender of a person. A person can be Male or Female. He cannotbe
both.
So, if the user has first selected Male, and if tries to select Female, the initialMale
selection he made should automatically get de-selected.
Another example would be when you want the user to select his or her favorite
colour.
In short, if you want to provide the user with mutually exclusive options, then
choose a Radio Button Control.
Page 16
Unit:2 Server Control
Important Properties of the Radio Button Control
Checked - This is a boolean property, that is used to check if the button is checkedor
not.
Text - This is string property used to get or set the text associated with the radio
button control
TextAlign - right or left. On which side of the radio button the text should appear
AutoPostBack - Set this property to true, if you want the webform to be posted
immediately when the checked status of the radio button changes.
Group Name - By default, the individual radio button selections, are not mutually
exclusive. If you have a group of radio buttons, and if you want the selectionsamong the
group to be mutually exclusive, then use the same group name for allthe radio button
controls.
Events
CheckedChanged - This event is fired when the checked status of the radio button
control is changed.
11.Radiobuttonlist:
RadioButtonList control is a single control that groups a collection of radio buttons.
Note:RadioButtonList controls supports the same set of properties as the CheckBoxList control does.
12.Adrotator:
Adrotator control is used to display random ads.
The ads information can be stored in an xml file or in a database table.
In this session we will discuss about using an XML file.
XML file attributes
1. ImageUrl - The URL of the image to display
2. NavigateUrl - The URL to navigate to, when the ad is clicked
3. AlternateText - The text to use if the image is missing
4. Keyword - Used by the adrotator control to filter ads
5. Impressions - A numeric value (a weighting number) that indicates thelikelihood
of how often the ad is displayed.
Page 18
Unit:2 Server Control
For example, when the AdRotator control is on a master page, and if you want to
change the KeywordFilter on each content page based on the keyword density, so
that, only the ads targeting the page content can be displayed.
Validation Control:
ASP.NET validation controls validate the user input data to ensure that useless,
unauthenticated, or contradictory data don't get stored. ASP.NET validation controls define an
important role in validating the user input data. Whenever the user gives the input, it must
always be validated before sending it across to various layers of an application. If we get the
user input with validation, then chances are that we a resending the wrong data So, validation is
a good idea to do whenever we are taking input from the user.
Page 19
Unit:2 Server Control
The best approach is always to perform client-side validation first and then,after the form passes
and is posted to the server, to perform the validation checks again using server -side validation.
Validate It per forms validation on the associated input control and up dates the IsValid
property.
Required Filed Validator Control:
1) RequiredFieldValidatorControl:
This is the simplest validation control that makes sure that the users have entered data into a Data-entry
control. Suppose that the users are entering data for buying shoes in Data-entry control. In that case you may
want to make sure that the users enter the number of shoes they want to buy. If they omit to enter a value, this
validation control will display its error message.
This control has an Initial value property, which is set to an empty string (“”) by default. If the data has not
changed from that value when validation occurs, the control displays its error message.
Properties:
Property Description
Initial Value Specifies the starting value of the input control.Default value is""
2)RangeValidatorControl:
A Range validator tests if thevalue of a Data-Entrycontrol is inside a specified range of values. You use three
main properties- ControToValidate, MinimumValue and maximumValue. The ControlToValidte property
contains the Data-Entry control to validate, MinimumValue and MaximumValue properties holdthe minimum
and maximum values of the valid range. If you set one of the MinimumValue and MaximumValue properties,
you also must set the other. Also set the Type property to the data type of the value to compare, the possible
values are the same as for comparison validators.
Properties:
Property Description
MaximumValue Specifies the maximum value of the input control
MinimumValue Specifies the minimum value of the input control
Type Specifiesthedatatypeofthevaluetocheck.Thetypesare:
Currency
Date
Double
Integer
String
Page 21
Unit:2 Server Control
3)CompareValidatorControl:
A CompareValidator compares the value entered bythe user into a Data-Entry control with the
value entered into another Data-Entry control or with a constant value. As usual for validation
controls, you indicate the Data-Entry control to validate by setting the ControlToValidate property. If
you want tocompare a specific Data-Entry control to another, set the ControlToCompare propertyto
specify the control to compare with.You can also compare Date-Entry value to the constant value,for
that you have to set the ValueToCompare property.
Use theType property to specify the type of comparision to perform.Here are the possibilities:
Operator Discription
Equal Checks if the compared value are equal.
NotEqual Checks if the compared value are not equal.
GreaterThan Checks for the greater than relationship.
GreaterThanEqual Checks for the greater than or equal relationship.
LessThan Checks for the less than relationship.
LessThanEqual Checks for the less than or equal relationship.
DataTypeCheck Compares data types between the value enteres into the Data-Entry
control being validated and the data type specified by theType property
Properties:
Property Description
ControlToCompare The name of the control to compare with
Operator The type of comparison to perform.The operators are:
Equal
GreaterThan
GreaterThanEqual
LessThan
LessThanEqual
NotEqual
DataTypeCheck
ValueToCompare A specified value to compare with
4)RegularExpressionValidatorcontrol:
A regular expresson Validator control is used To Check if the value in data-Entry control
matches a
Pattern defined By a regular expression.You use regular expression to See if the text Matches a
certain Pattern, Which Is A Great Way to Check If The User Has Entered Text In The Way You
Want.
Property Description
ValidationExpression Specifies the expression used to validate input control. The expression
validation syntax is different on the client than on the server. Jscript is used
on the client. On the server, the language you have specified is used
Page 22
Unit:2 Server Control
5)CustomValidator control:
ASP.Net also allows the freedom of writing your own validator. This eases the task of a
developer to validate the form at the client side itself. It also allows putting more
complex validations in place. Validations that are business or application-specific can
be written using custom validators.
The custom validation code is written in a function in the code-behind page and
the function name is passed as an attribute to the Custom Validator class .
Custom validation can be done either at the client-side or the server-side.
Client Validation Function property specifies that the validation is to be
performed on the client-side. Such validation code must be written in some
scripting language such as JavaScript, VBScript,etc.
The Server Validate event handler is used when validation has to be done
on the server-side. The server-side validation routine is written in C#, VB
.Net or any other .Net language.
With a custom validator, you set the ClientValidation function property to the
names of a script function, such as Javascript or VBscript function. This function will
pass two arguments- sources and arguments. Source gives the source control to
validate, and arguments, hold data to validate as arguments.Value. if you validate the
data, you set arguments.IsValid to TRUE else to FALSE.
Using custom validatoris perhaps the most powerful way to use validators.Existing
beyond the
Simple range checking and field checking validators,custom validators also let you write your
own customization code.
Property Description
Page 23
Unit:2 Server Control
Property Description
DisplayMode Howto display the summary.Legal values are:
BulletList
List
SingleParagraph
EnableClientScript A Boolean value that specifies whether client-side validation
is enabled or not
Enabled A Boolean value that specifies whether the validation control is
enabled or not
ForeColor The fore color of the control
HeaderText A header in theValidation Summary control
ShowMessageBox A Boolean value that specifies whether the summary should be
displayed in a message box or not
ShowSummary A Boolean value that specifies whether theValidation Summary
control should be displayed or hidden
ValidationGroup Sets the group of controls for which the validation Summary object
displays validation messages.
MasterPage:
Master pages provide templates for other pages on your website. Master pages
allow you to create a consistent look and behaviour for all the pages (or group of
pages) in your web application.
A master page provides a template for other pages,with shared layout and
functionality.The master page defines placeholders for the content, which can be
overridden by content pages. The output result is a combination of the master page
and the content page.
Page 24
Unit:2 Server Control
MasterPageKey Points:
Page 25
Unit:2 Server Control
Page 26
Unit:2 Server Control
Page 27
Unit:2 Server Control
Page 28
Unit:2 Server Control
That's it we are done. Run the application and notice that SiteMapPath control
displays the navigation path. The SiteMapPath control automatically reads data
from Web.sitemap file.
Page 29
Unit:2 Server Control
NavigateUrl="~/UploadResume.aspx" Target="_blank"/>
<asp:TreeNode Text="Edit Resume"
NavigateUrl="~/EditResume.aspx"
Target="_blank"/>
<asp:TreeNode Text="View Resume"
NavigateUrl="~/ViewResume.aspx"
Target="_blank"/>
</asp:TreeNode>
<asp:TreeNode Text="Employer"
NavigateUrl="~/Employer.aspx"
Target="_blank">
<asp:TreeNode Text="Upload Job"
NavigateUrl="~/UploadJob.aspx" Target="_blank"/>
<asp:TreeNode Text="Edit Job"
NavigateUrl="~/EditJob.aspx"
Target="_blank"/>
<asp:TreeNode Text="View Job"
NavigateUrl="~/ViewJob.aspx"
Target="_blank"/>
</asp:TreeNode>
<asp:TreeNode Text="Admin" NavigateUrl="~/Admin.aspx"
Target="_blank">
<asp:TreeNode Text="Add User"
NavigateUrl="~/AddUser.aspx" Target="_blank"/>
<asp:TreeNode Text="Edit User"
NavigateUrl="~/EditUser.aspx" Target="_blank"/>
<asp:TreeNode Text="View User"
NavigateUrl="~/ViewUser.aspx" Target="_blank"/>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
Page 30
Unit:2 Server Control
To configure the look and feel of the TreeView control, the following styles
can beused.
1. HoverNodeStyle
2. LeafNodeStyle
3. RootNodeStyle
4. SelectedNodeStyle etc.
LoginControls
Internet is emerging as the most widely used medium for performing various
tasks, such as online shopping ,Data exchanging and bank transactions etc. All this
Information and data need to be secured against unauthorized access from illegal sources.
For this purpose, we use authentication and authorization process.
We need to write large piece of code to create forms and user interfaces for authenticating
the user and displaying the desired page based on the roles or rights given to the user. But it is
very time consuming so that Microsoft developed a new series of server controls, called login
controls.
To use login controls in your website. You just need to drag and drop them on the web page.
There is no need to write more codes in the codes-behind file. The Login controls have built in
functionality for authentication and authorization of users.
This membership services is an important feature of ASP.NET that helps you validating and
storing user credentials.
The ASP.NET Membership services helps to implement the following functionalities in an
application.
Page 31
Unit:2 Server Control
The Login Controls:
1. Login
2. LoginView
3. LoginStatus
4. Loginname
5. PasswordRecovery
6. ChangePassword
7. CreateUserWizard.
The Login control provides a user interface which contains username and password that
authenticate the username and password and grant the access to the desired services on the
basis of the credentials.
The Login class contains various methods, properties, and events to work with. Some of them are
as listed below:
1. CreateChildControls: It creates an individual control of the Login control and the event
handlers are associated with it.
2. OnLoggingIn: It raises the LoggingIn event when the user adds the login data
before the authentication is completed.
3. OnLoggedIn: It raises an LoggedIn event when the user loginto the web site after the
authentication is completed
4. OnAuthenticate: It raises an Authenticate event for the user authentication.
1. CreateUserIconUrl: It retrieves the location of the image to display the link to the user.
2. CreateUserUrl: It specifies or retrieves the URL for the new user page.
3. DisplayRememberMe: It specifies the value stating whether to display the RememberMe
checkbox.
4. FailureText: It displays the text when the login attempt fails
5. HelpPageText: It specifies the text of link to the login help page.
6. Password: It retrieves the password entered by the user
Events of the Login Control
1. LoggedIn: It is initiated when the user logs in the web site and is authenticated.
2. LoggingIn: It is initiated when the user submits the login information.
3. LoginError: It is initiated when a login error is detected.
2.) The LoginView Control:-
The LoginView Control is a web server control, Which is used to display two different views of a
web page of any website , depending on whether the any user has logged on to a web page as
anonymous user or registered user .If the user is authenticated, the control displays the appropriate
to the person with the help of the following views template.
Page 32
Unit:2 Server Control
Anonymous Template :- This template (default of all) will be displayed when any
user just open the web page but not logged in.
LoggedInTemplate:- This Template (page)will be displayed when the user in logged in.
RoleGroups:- This template will be displayed when user logged in, that is the member of
thespecific role (defined role group).
You can drag and drop Loginview Control on the web page from toolbox as shown below:-
The LoginView class provides the LoginView control. The methods, properties and events
provided by the login class are as listed below:
1. DataBind: It helps user to bind the data source through the LoginView control.
2. OnViewChanged: It raises the ViewChanged event after the view for the control is changed.
3. OnViewChanging: It raises the ViewChanging event before the LoginView control
changes the view.
1. Controls: It accesses the ControlCollection object containing the child controls for the
LoginView control
2. EnableTheming: It access or specifies the value indicating the themes to be applied to the
control
3. RoleGroups: It access the collection of role groups associated with the content templates.
Page 33
Unit:2 Server Control
Methods of the LoginStatus Control
1. OnLoggedOut: It raises the event when the logout link is clicked by the user.
2. OnLoggingOut: It raises the event when the user clicks the logout link of the
control.Properties of the LoginStatus Control
1. LoginImageUrl: It accesses or specifies the URL of the image used for the login link.
2. LoginText: It access the text added for the login link
3. LogoutAction: It retrieves the value for determining the action when the user logs out of the
web site.
4. LogoutText: It retrieves the text used for logout the link.
1. LogginOut: It is initiated when the user sends the logout request to the server.
2. LoggedOut: It is initiated by the LoginStatus class when the user logout process is completed
It is used for displaying the name of the authenticated users. The Page.User.Identity.Name is
used for returning the user name. The control is not displayed if it does not contain any
logged in user. The LoginName class is used for the control.
The control does not contain any method, property or events associated with it. The FormatString
property is used for displaying the string in the control.
It is used to recover or reset the password for the user. The password is sent through an email as a
message at the registration time. The Membership service is used for creating and resetting the
password.
The control contains the following three views.
1. Question: It refers the view where the user can enter the answer to the security question.
2. UserName: It refers to the view where the user can enter the username for the password to be
recovered.
3. Success: It represents the view where the message is displayed to the user.
The control contains various properties, methods and events as mentioned below:
1. OnSendingMail: It raises the SendingMail event when the user is verified and the password
is sentto the user.
2. OnUserLookupErrror: It raises the UserLookupError when the username does not match
with the one stored in the database,
3. OnSendMailError: It raises an error when the mail message is not sent to the user.
4. OnVerifyingUser: It raises the event once the username is submitted, and the membership
provider verification is pending.
Page 34
Unit:2 Server Control
Properties of the control
1. Answer: The answer provided by the user to confirm the password recovery through the valid
user.
2. FailureTextStyle: It accesses the reference to the collection of properties defining the error
text look.
3. HelpPageIconUrl: It image to be displayed for the link to the password is retrieved.
1. SendingMail: It is initiated when the server is sending an email message containing the
password once the answer is correct.
2. AnswerLookupError: It is initiated when the user answer to the question is incorrect.
3. VerifyingAnswer: It is initiated when the user has submitted the answer to the password
recovery confirmation question.
6. ) CreateUserWizard control:-
The control uses the Membership service for creation of a new user. The control can be
extended to the existing Wizard control. The control can be customized through templates and
properties.
Some of the properties, methods and events related to the control are as mentioned below:
Properties of the Control
1. Answer: It retrieves or specifies the answer to the password recovery confirmation question.
2. CompleteStep: It shows the final step of the process for creating the user account.
3. ContinueButtonText: It accesses or specifies the collection of properties defining the
look of the control
4. Email: It retrieves the email address of the user
5. LoginCreatedUser: It accesses or specifies the value indicating the new user login once the
account is created.
Events of the control
1. CreatedUser: It is initiated after the membership service provider has created a new user
account
2. CreatingUser: It is initiated before the membership service provider is called for
creating user account
3. SendingMail: It is initiated before sending the conformation email on the successful
creation ofthe account
4. SendMailError: It is initiated when the SMTP error occurs during the mail sent to the user.
7.) The ChangePassword Control:-
Using this control ,user can easily change your existing password (old password) on the ASP.NET
Website.This control prompts uses to provide the current password first and then set the new
password first and then set the new password.If the old password is not correct then new password
can't be set. This is also helps to send the email to the respective users about the new password.This
control is used ChangePassword class.
Page 35
Unit:2 Server Control
Properties of the control:
1. CancelDestinationPageUrl: It accesses or retrieves the URL of the page that the user is
shown once it clicks the Cancel button.
2. CurrentPassword: It retrieves the current password of a user.
3. DisplayUserName: It retrieves the value indicating whether the ChangePassword control
should be display the control and label.
4. NewPassword: It retrieves the new password entered by the user.
5. UserName: It shows the username for which the password is to be modified.
Consider an example to demonstrate the login controls in an ASP.NET application. Perform the
following steps to demonstrate the implementation of the login controls in application.
1. Place the login control in the .aspx form and change the AutoFormat style property to
Classic.
2. Click the Smart Tag and open the Login Tasks and select the Administer Website option.
3. Click the Security link in the window.
4. Click the Use the security Setup Wizard to configure security step by step link to open the
setup wizard.
5. Click Next button in the welcome the security setup wizard.
6. Click the From the Internet radio button and click the Next button.
7. Click the Next button in the Advance provider settings page.
8. Select the Enable roles for this web site check box and click the Next button.
9. Add the details in the text boxes and click the Create User button to create the user account.
10. Select the All Users radio button in the Rule applies to section.
11. Click the Add this Rule button. Click Next button.
12. Click Finish button, click Close button.
13. Add the LoginName and LoginStatus controls on the web page.
14. Set the LogoutAction property to Redirect, click the smart tag of the LoginStatus
control andselect the Logged In option from the Views drop down list.
15. Execute the application and enter the username and password in the text boxes. Click Log In
button.
Page 36