ASP.Net Unit-2 Ꮢ.ꪜ
ASP.Net Unit-2 Ꮢ.ꪜ
N
www.jump2learn.com PUBLICATIO
ASP.NET
Jump2Learn The Online Learning Place
LS
Server Control
Server controls are basically used to provide communication between client side and server
side. These are the main 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.
.HTML server controls These controls are basically standard controls enhanced to
enable server side processing.
Login controls- These controls provide user authentication.
Navigation controls These controls help in navigation. For example, menus, tree
view etc.
Master pages These controls provide consistent layout and interface throughout
the application.
Syntax for using server control:
Visual studio is also providing some extra features which help to produce error free coding:
There is a feature of Intellisense which displays and auto completes the properties of
control.
Post back is actually sending all the information from client to web server, then web server
process all those contents and returns back to the client. It is done if certain credentials of
the page are to be checked against some sources (such as verification of username or email
ld and pasword using database). Most of the times ASP control will cause a post back fe. 8.
buttonclick) but some don't unless you tell them to do.
In certain events (
Listbox Index Changed, RadioButton Checked etc.) in an ASP.NET page
IsPostBack Property
IsPostBack is a propety of the Asp.Net page that tells whether or not the page is on its
initial load or if a user has perform a button on your web page that has caused the page to
post back to itself.
The value of the Page IsPostBack property will be set to true when the page is executing
after a post back, and false otherwise. We can check the value of this property based on the
value and we can populate the controls on the page.
IsPostback is normally used on page _load event to detect if the web page is getting
generated due to post back requested by a control on the page or if the page is getting
loaded for the first time.
if (!IsPostBack)
else
4 Unit-2 Server Control
Iblpostback.Text "Hello"
In ASP.NET, the word "data binding" simply indicates that the data obtained from a source is
bound to the controls that enable read and write access to the data. Databases, XML files,
flat files, and other data sources are some of the data sources we're discussing.
The process of establishing a connection between the Aplication User Interface and the
Data is known as data binding.
One can wonder what the difference is between that and displaying data on a user
interface. There is a significant distinction. The distinction is that if the data binding is
incorrect, any changes to the data will not be reflected in the user interface.
In ASP.NET, there are two forms of data binding: basic data binding and declarative data
binding. Some controls support both types of data binding, while the remainder only
support basic data binding.
When the expression is evaluated, the difference between data binding tags and normal
code insertion tags <% and %> becomes apparent.
When the DataBind method in the Page objects or Web control is called, expressions within
the data binding tags are evaluated.
Data Bind Control can display data in connected and disconnected model.
GridView Control
ListBox Control
Datalist Control
Unit-2 Server Control
Repeater Control
DetailsView Control
FormView Control
The GridView control enables us to display, select, sort, page, and edit data items such as
database records.
The GridView control is a feature rich and versatile control used to accept, display, and edit
To use a GridView control a DataSource control has to be attached to the GridView control.
The property DataSourcelD of the GridView control binds the Gridview control to the
DataSource control and allows paging, sorting and database operations with the
DataSource.
SortExpression Gets the current sort expression (ield name) that determines
DataSource Gets or sets the data source object that contains the data to
populate the control.
DataSourceld Indicate the bound data source control to use (Generally used
when we are using SqlDataSource or AccessDataSource to
Unit-2 Server Control
AlternatingRowStyle Defines the style properties for every alternate row in the
GridView.
EditRowStyle Defines the style properties for the row in EditView (When you
click Edit button for a row, the row will a ppear in this style).
EmptyDataRowStyle Defines the style properties of the empty row, which appears if
there is no records in the data source.
HeaderStyle Defines the style properties of the header of the GridView. (The
column header appears in this style.)
CellPadding Indicates the space in pixel between the cells and the border of
the GridView.
EmptyDataText Indicates the text to appear when there is no record in the data
source.
ShowHeader Indicates whether the header should appear or not. (The column
name of the GridView)
Columns Gets the collection of objects that represent the columns in thee
GridView.
Editlndex Gets or sets the 0-based index that identifies the row currently to
be edited.
Unit-2 Server Control
PageCount Gets the number of the pages required to display the reocrds of
the data source.
DatakeyNames Gets an array that contains the names of the primary key field of
the currently displayed rows in the GridView.
PagelndexChanging, Both events occur when the page link is clicked. They fire before
PagelndexChanged and after GridView handles the paging operation respectively
RowDeleting, RowDeleted Both events fires when Delete button of a row is clicked. They
RowEditing Fires when a Edit button of a row is clicked but before the
GridView hanldes the Edit operation.
RowUpdating, Both events fire when a update button of a row is clicked. They
Sorting, Sorted Both events fire when column header link is clicked. They fire
before and after the GridView handler the Sort operation
respectively.
Example:
DataKeyNames="ID" DataSourcelD="AccessDataSource1"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
<Columns>
SortExpression="ID"/>
SortExpression="gender" /
10 Unit-2Server Contral
SortExpression="userld" />
SortExpression="Passwrd" />
</Columns>
/asp:GridView
DataFile=JApp_Data/StudentDB.accdb"
SNAME-@SNAME,GENDER=@GENDER, USERID=@USERID,PASSWRD=@PASSWRD
WHERE ID=@ID>
</asp:AccessDataSource
The ListBox control is used to provide the user with a single or multiple select options from a
list of things.
All characteristics and functionality are similar to the DropDown List box. ListBox, on the
other hand, contains two additional properties: Rows and SelectionMode. The ListBox
control is used to give the user a single or multiple select choice from multiple listed items
(depending on the property set).
Unit-2 Server Control-
You can set its height and width in pixels by specifying its height and width, but you won't
The <select/> HTML tag is used to implement it when it is rendered on the page. Combo box
is another name for it.
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.
DataTextField Name of the data source field to supply the text of the items.
(No need to set when you are adding items directly into .aspx
page.)
DataValueField Name of the data source field to supply the value of the items.
(No need to set when you are adding items directly into .aspx
page.)
DataSource The datasource that populates the items in the listbox box.
(Generally used when you are dynamically generating the items
from Database.)
12 Unit-2Server Contral
AppendDataBoundltems true or false. If true, the statically added item (added from .aspx
page) is maintained when adding items dynamically (from code
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.)
Example:
/ Listbox 1
</asp:ListBox>
I/ Listbox 2
<asp:list Box ID="ListBox1" runat="Server"/
// Listbox 3
I/Listbox 4
The Datalist Control is a databound control that displays data by using templates.
These templates define control and HTML elements that should be displayed for an item.
Like the GridView, the Datalist renders as an HTML <table>, but allows for multiple data-
source records to be displayed per table row.
1) itemTemplate
2) AlternatingitemTemplate
3) HeaderTemplate
4) FooterTemplate
5) SeperatorTemplate
1) ItemTemplate: ItemTemplate defines how the each item is rendered from data source
collection.
collection.
14 Unit-2 Server Control
cHeaderTemplate>
/HeaderTemplate>
<ltemTemplate
</temTemplate>
<FooterTemplate>
</FooterTemplates
s/asp:Datalist>
Example:
DataSourcelD="SqIDataSource1">
cHeaderTemplate
Details
</HeaderTemplate
<FooterTemplate>
nd
Unit-2 Server Control
/FooterTemplate>
<ltemTemplate>
ID:
<br/
name:
<br/>
gender
username:
<br/>
password:
<br/
<br/>
</ltemTemplate>
<Jasp:DataList>
16 Unit-2 Server Control
1. ItemDataBound
2. DataBound
1. ItemDataßound:
The ItemDataBound occurs after any control's object has been created its properties
have been initialized with values retrieved from corresponding data fields.
By accessing the data bound item via the event argument's controlname.ltem property and
modifying its settings 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 processed,
this event happens.
By giving a handler to the DataBound event, you can additionally implement extra logic at
this time.
Repeater Control is a control which is used to display the repeated list of items.Repeater
Control is used to display repeated list of items that are bound to the control and it's same
as datagridview. Repeater control is lightweight and faster to display data when compared
with gridview. By using this control we can display data in custom format.
1) itemTemplate
2) AlternatingitemTemplate
3) HeaderTemplate
Unit-2 Server Control
4) FooterTemplate
5) SeperatorTemplate
1) ItemTemplate: ItemTemplate defines how the each item is rendered from data source
collection.
</HeaderTemplate
<ltemTemplate>
</ltemTemplate>
FooterTemplate
</FooterTemplate>
s/asp:Repeater
<HeaderTemplate»
<tr
Id
</th>
Name
</th>
Gender
</th>
/tr>
</HeaderTemplate>
<ltemTemplate>
<tr>
<td>
</td>
<tds
</td>
Unit-2 Server Control 19
<td
<asp:label lID="IblCountry" runat="server"
</td>
</t
</ItemTemplate>
FooterTemplates
</table>
</FooterTemplate
/asp:Repeater
DetailsView Control
DetailsView server control is used to display, delete, insert or edit a single record from data
source.
DetailsView control has seven types of fields, every with different purpose:
1) BoundField - This is default field, used when AutoGenerateRows is true. You can use
4) CommandField Command buttons, like Edit, Delete or New, used for manipulating
-
data.
7) TemplateField Used to show data in custom layout, when other field types are
inadequate.
Example:
20 Unit-2 Server Control
<Fields>
SortExpression="gender"/>
SortExpression="userld"/
SortExpression="Passwrd"/>
/Fields>
s/asp:DetailsView>
The main difference between FormView and DetailsView controls is that FormView control
allows using of templates for displaying a record instead of row fields used in DetailsView.
Developer needs to create a template first and specify controls and formatting to display
single record from data source. Because of that developer have full control over layout and
it is pretty easy to add validation capabilities.
Unit-2 Server Control 21
FormView template consists from three parts: for viewing a record, edit a record, and add
new record. Also, you can use it for browsing and deleting of records and include formatting
for header and footer elements.
HeaderTemplate
.ItemTemplate
InsertltemTemplate
EditltemTemplate
EmptyDataTemplate
PagerTemplate
FooterTemplate
Example:
<EditltemTemplate>
ID:
cbr/
sname:
<br/
gender:
cbr/>
userld:
22 Unit-2 Server Control
br
Passwrd:
<br/
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" /
</EditltemTemplate
<lnsertltemTemplate
ID:
sname:
<br />
gender:
<br/>
userld:
<br/
asswrd:
<br />
CommandName="Insert" Text="Insert"/>
</InsertitemTemplate
<ltemTemplate>
ID
<asp:label 1D="IDLabel" runat="server" Text=<96# Eval("ID") 6>/>
br
sname:
br,
gender:
<br/>
userld:
<br/>
Passwrd:
Unit-2 Server Control
<br/>
</ItemTemplate>
</asp:FormView>
Web forms controls are provided by ASP.NET and are used to construct HTML components.
These controls are divided into two categories: server and client.
ItemCreated,
ItemDataBound
Datalist CancelCommand, It is used to create datalist that is non-tabular
EditCommand, and used to show data.
DeleteCommand,
ItemCommand,
SelectedindexChanged,
UpdateCommand,
ItemCreated,
ItemDataBound
CheckBox CheckChanged It is used to create checkbox.
CheckBoxlist SelectedindexChanged It is used to create a group of check boxes
that all work together.
RadioButton CheckChanged | It is used to create radio button.
RadioButtonlist SelectedindexChanged It is used to create a group of radio button
controlsthat all work together.
Image None It isusedtoshowimage within the page.
Panel None It is used to create a panel that works as a
container.
PlaceHolder None used to set placeholder for the control.
It is
Calendar Selection Changed, It is used to create a calendar. We can set the
VisibleMonthChanged, default date, move forward and backward
DayRender etc.
AdRotator AdCreated It
allows us to specify a list of ads to display.
Each time the user re-displays the page.
Table None | It is used to create table.
XML None It is used to display XML documents within
the HTML.
Literal None It is like a label in that it displays a literal, but
allows us to create new literals at runtime and
place them into this control.
Table 2.7 Web Server Controls
The HTML server controls are basically the standard HTML controls enhanced to enable
server side processing.
The HTML controls such as the header tags, anchor tags, and input elements are not
processed by the server but are sent to the browser for display.
26 Unit-2Server Control
They are specifically converted to a server control by adding the attribute runat="server"
and adding an id attribute to make them available for server-side processing.
HtmlHead <head>element
HtmlInputButton <input type=button submit| reset>
HtmlinputCheckbox <input type=checkbox
HtmllinputFile cinput type = file>
HtmllnputHidden <input type = hidden>
B,HTML
Pointer
Ohput (Butten)
Input (Reset)
Input (Submit)
Input (Tert CotentiaceHolderz (Cutom
Input
Input
(File)
(Password)
BrowseP
Input (Chechbex)
O Input (Radio)
input(Hidden)
Validation Control
ASP.NET validation controls validate the user input data to ensure that useless,
unauthenticated, or contradictory data don't get stored.
If user enters values that do not match the validation criteria, you can show appropriate
message to the user.
RequiredFieldVal idator
RangeValidator
CompareValidator
RegularExpressionValidator
CustomValidator
28 Unit-2 Server Control
ValidationSummary
RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not empty. It is
generally tied to a text box to force input into the text box.
</asp:RequiredfieldValidators
RangeValidator Control
The RangeValidator control verifies that the input value falls within a predetermined range.
It has three specific properties:
Properties Description
Type It defines the type of the data. The available values are: Currency
Date, Double, Integer, and String.
MinimumValue It specifies the minimum value of the range.
MaximumValue It specifies the maximum value of the range.
Table 2.9 Properties of RangeValidator Control
</asp:RangeValidator
CompareValidator Control
The CompareValidator control compares a value in one control with a fixed value or a value
in another control.
It has the following specific properties:
Properties Description
Unit-2 Server Control
ControlToCompare="txt Password">
</asp:Comparevalidator
RegularExpressionValidator Control
The following table summarizes the commonly used syntax constructs for regular
expressions:
Apart from single character match, a class of characters could be specified that can be
matched, called the metacharacters.
Metacharacters Description
Matches any character except \n.
Quantifier Description
Zero or more matches.
One or more matches.
IN N matches.
N,} N or more matches.
N,M} Between N and M matches.
ValidationExpression="\w+{l+:]\w+)*@\w+(-J\w+}*\w+{[-Jw+)*"
</asp:RegularExpressionValidator>
Unit-2 Server Control 31
[2-9]1210-9]18}S
the open and the close curly bracket are used as range quantifiers.
II the open and close square bracket defines a character class to match a single
character.
CustomValidator Control
The CustomValidator control allowS writing application specific custom validation routines
for both the client side and the server side validation.
The client side validation is accomplished through the ClientValidation Function property.
The client side validation routine should be written in a scripting language, such as
JavaScript or VBScript, which the browser can understand.
The server side validation routine must be called from the control's ServerValidate event
handler. The server side validation routine should be written in any .Net language, like C# or
Net.
if fargs.Value.Length== 8)
args.lsValid = true;
else
args.lsValid = false;
ValidationSummary Control
Unit-2 Server Control
The ValidationSummary control does not perform any validation but shows a summary of al
errors in the page. The summary displays the values of the ErrorMessage property of all
validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
Navigation Control
Navigation controls are basically used to navigate the user from one page to other.
There are three controls in ASP.NET, Which are used for Navigation on the webpage.
.TreeView control
Menu Control
SiteMapPath control
TreeView Control
The TreeView control is used for logically displaying the data in a hierarchical structure.We
can use this navigation control for displaying the files and folders on the webpage.W can
easily display the XML document,Web.SiteMap files and Database records in a tree
structure.
There are some types to generate navigation on webpage through TreeView control.
The top level in a tree view is root nodes that can be expanded or collapsed if the nodes
have child nodes
The TreeView supports both postback-style events and simple hyperlink navigation.
Valldatio Root
Navigation S Paent
Pointer Leaf
SitelapPath_ Leaf 2
TreeView Parent 2
Menu Leaf 1
Login Leaf 2
WebParts
The user can expand the TreeNode by clicking the plus sign (+) button, if one is displayed
next to the TreeNode.
Properties Description
Nodes Gets a collection of TreeNode objects that represents the root nodes in
Event Description
TreeNodeCheckChanged Fired after the check state of node changed
Menu Control
Unit-2 Server Control
The Menu control is used to create a menu of hierarchical data that can be used to navigate
through the pages. The Menu control conceptually contains two types of items.
First is StaticMenu that is always displayed on the page, second is DynamicMenu that
appears when opens the parent item.
Properties Description
DataSourcelD Indicates the data source to be used (You can use .sitemap
file as datasource).
Event Description
MenultemClick{) Fired after an item has been clicked
SeriotManaaer SeripthManagerl
BspiiehuacndL
Hame ogin adminhomeHaw 1tem
SiteMapPath Control
The SiteMapPath control is also used to display the Navigation information on the site.It
display the current page's context within the entire structure of a website.
B Navigation
Pointer
SiteMapPath Root Node Parent Node >Curent Node
Treeview
Menu
Table 2.18 SiteMapPath Control
Login Control
Login control provides a ready-to-use user interface that may be used as a web site's login
interface. Internally, it is implemented using the <table>«/table> HTML tag when it is
presented on the page.
Properties Description
TitleText Indicates the text to be displayed in the heading of the
control.
InstructionText Indicates the text that appears below the heading of the
control.
UserNamelabelText Indicates the label text of the username text box.
PasswordlabelText Indicates the label text of the password text box.
FailureText Indicates the text that is displayed after failure of login
attempt.
UserName Indicates the initial value in the username text box.
LoginButtonText Indicates the text of the Login button.
LoginButtonType Button/Link/Image. Indicates the type of login button.
Destination Page Url Indicates the URL to be sent after login attempt successful.
DisplayRememberMe true/false. Indicates whether to show Remember Me
checkbox or not.
VisibleWhenLoggedin true/false. If false, the control is not displayed on the page
when the user is logged in.
Properties Description
Properties Description
Authenticate Fires to authenticate the user. This is the function where you
Example:
ForeColor="#333333" OnAuthenticate="Login1_Authenticate"
OnLoginError="Login1_LoginError">
TextBoxStyle Font-Size="o.8em"/>
</asp:Login>
Log In
User Name:
Password:
Log In
Register User
Forget password?
It allows you to create a consistent layout for the pages in your application.
3. Select Master Page option from Add new item Dialog Box.
6. Add desired controls on the master page that you want on all the pages.
Drag and Drop HTML Table and then keep all controls.
3. Give Proper name to the web form and Check Select master page option at
t 1webthe Cortrd
**
soe s
e we
Cre te web Carhgn
Clan ag
y femeletr
Afam fo ob kccek
Nane: te.p
Lga
Erotfokbersr
8anePaetet Msterfageore.nastr
MasterPageFile="-/MasterPage.master"
40 Unit-2 Server Control
<asp:Content ContentPlaceHolderlD="ContentPlaceHolder1"
runat="server"></asp:Content>
-</asp:Centent>
OR
You can directly go to design section of .aspx page and from contentPlaceHolder select
Themes
They are skin template that allows you to define the look of pages and controls, which can
then be applied to all the pages in your application to provide consistent look for your
application.
It is used to set Height, width, Forecolor, backcolor, bordercolor of any asp.net server
controls.
Unit-2 Server Contro
4. Alert will ask to add Skinfile in ApP_Themes folder. Click Yes button.
Example:
2. Right click on page-> go to properties-> In Theme property select the SkinFile that you
have created.
Note: This step is only useful when you have not applied master page to the form.
There are two types of control skins, default skins and named skin:
A default skin automatically applies to all controls of the same type when a theme is
applied to a page. A control skin is a default skin if it does not have a SkiniD attribute.
For example, if you create a defalt skin for a Calendar control, the control skin
applies to ll Calendar controls on pages that use the theme. (Default skins are
A named skin is a control skin with a SkinlD property set. Named skins do not
automatically apply to controls by type. Instead, you explicitly apply a named skin to
a control by setting the control's SkinlD property. Creating named skins allows you to
set different skins for different instances of the same control in an application.
You can apply lots of style sheets to a page, but usually you'll only create one. First choose
to create a new file
Solution Explorer
Image 2.8 Right-click, as ever, on your project in Solution Explorer and choose to add a new
item
TM
2. Give your style sheet a name (often calling it after the website works well).
You can now start editing your style sheet as shown below.
Editing Styles
There are two ways to edit styles. The first way (and easier way, when you learn the
language) is to type them in directly:
BlogExample.cssx
/*the
body
font used throughout */
font-family: Verdana;
font-size: 12px;s
The other way is to right-click on a style and chooses to build it, although you still have to
find your way round the dialog box which appears:
Unit-2 Server Control
44
BlogExample.css x
the font used throughout */
body
font-family: Verdana;
f Cut Ctri-X
aCopy Ctr+C
Paste Ctl-V
X Delete Del
Build Style
1. Open the page for editing in Design view (here we're using the master page).
O BlogExample.master
Default.aspx
web.config
Here's how Visual Studio will amend the HTML of your page to reflect the change (it inserts
a link to the style sheet in the head section of the page):
Unit-2 Server Control
BlogExample.masterXI
|BlogExample.master Xx
UUUyy.
bodyl
To-do list website
To-do ist website
CSS:
5. The CSS cannot override the property values defined for a control.
Themes:
46 Unit-2 Server Contral
3. But we cannot apply multiple themes to a single page. Only one theme we can
5. For property values defined in a theme, the theme property overrides the
property values declaratively set on a control, unless the StyleSheetTheme
property is explicitly defined.
7. All theme and Skin files should be placed in a special Asp.net folder called the
9. But a theme can define multiple properties of a control not just style properties
such as we can specify the graphies property for a control, template layout of a
GridView control etc.
Questions