0% found this document useful (0 votes)
8 views

ASP.Net Unit-2 Ꮢ.ꪜ

The document provides an overview of server controls in ASP.NET, detailing their categories such as validation, data source, and navigation controls. It explains concepts like post back, the IsPostBack property, and data binding, along with examples of controls like GridView, ListBox, and DataList. Additionally, it outlines the properties and events associated with these controls, emphasizing their functionality in web application development.

Uploaded by

pansuriyanihar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

ASP.Net Unit-2 Ꮢ.ꪜ

The document provides an overview of server controls in ASP.NET, detailing their categories such as validation, data source, and navigation controls. It explains concepts like post back, the IsPostBack property, and data binding, along with examples of controls like GridView, ListBox, and DataList. Additionally, it outlines the properties and events associated with these controls, emphasizing their functionality in web application development.

Uploaded by

pansuriyanihar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Jump2Learn

N
www.jump2learn.com PUBLICATIO

DEVELORING WEB APPLICATIONS


WITH

ASP.NET
Jump2Learn The Online Learning Place

LS

Ms. Twinkle Panchal |


Ms. Krishna Khandwala |
Mr. Chirag Prajapati
Unit -2
Server Control
2 Unit-2 Server Control

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:

sasp:controlType ID ="ControliD" runat="server" Property1=valuel [Property2=value2]/>

Visual studio is also providing some extra features which help to produce error free coding:

.You can simply do drag and drop of controls in design view.

There is a feature of Intellisense which displays and auto completes the properties of
control.

We can set the property values directly by using property window.

2.1 Post back

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

upon which a Post Back might be needed.


Unit-2 Server Control

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.

Browser Web Server

Http "Get" myPage.aspx ( no datdISPostBack


First = false
Request for Response= myPage.aspx
myPage

Http "Post myPage.aspx ( data)IsPostBack =


User fills in true
form and Response= myPage.aspx
submits
data

2.1 IsPostBack Property

Example of IsPostBack on Page_Load Event:

protected void Page_Load{object sender, EventArgs e)

if (!IsPostBack)

Iblpostback.Text= "Good Morning":

else
4 Unit-2 Server Control

Iblpostback.Text "Hello"

2.2 Data Binding in ASP.NET

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.

Data binding uses a special syntax:


<%# 9%>

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.

Data bind Controls in ASP.NET

GridView Control

ListBox Control

Datalist Control
Unit-2 Server Control

Repeater Control

DetailsView Control

FormView Control

2.2.1 GridView 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

data on a web page. It is a commonly used control in ASP.Net web applications

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.

Property name Description

AllowPaging8 true/false. Indicate whether the control should support


paging.

Allowsorting true/false. Indicate whether the control should support


sorting

SortExpression Gets the current sort expression (ield name) that determines

the order of the row.


SortDirection Gets the sorting direction of the column sorted currently
(Ascending/Descending).

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

bind the data, See 1st Grid example).

AutoGenerateEditButton true/false. Indicates whether a separate column should be


added to edit the record.

AutoGenerateDeleteButton true/false. Indicates whether a separate column should be


added to delete the record.

AutoGenerateSelectButton true/false. Indicate whether a separate column should be


added to selecat a particular record.

AutoGenerateColumns true/false. Indicate whether columns are automatically


created for each field of the data source. The default is true.

Table 2.1 Behaviour Properties

Property name Description

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).

RowStyle Defines the style properties of the rows of the GridView.

PagerStyle Defines the style properties of Pager of the GridView. (If


AllowPaging=true, the page number row appears 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.)

FooterStyle Defines the style properties of the footer of Grid View.

Table 2.2 Style Properties


Unit-2 Server Control

Property name Description

CellPadding Indicates the space in pixel between the cells and the border of
the GridView.

CellSpacing Indicates the space in pixel between cells.

GridLines Both/Horizontal/Vertical/None. Indicates whether Grdilines


should appear or not, if yes Horizontal, Vertical or Both.

HorizontalAlign Indicates the horizontal align of the GridView.

EmptyDataText Indicates the text to appear when there is no record in the data
source.

ShowFooter Indicates whether the footer should appear or not.

ShowHeader Indicates whether the header should appear or not. (The column
name of the GridView)

BackimageUrl Indicates the location of the image that should display as a


background of the GridView.

Caption Gets or sets the caption of the GridView.

CaptionAlign left/center/right. Gets or sets the horizontal position of the


GridView caption.

Table 2.3 Appearance Properties

Property name Description

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

FooterRow Returns a GridViewRow object that represents the footer of the


GridView.

HeaderRow Returns a GridViewRow object that represents the header of the


GridView.

PageCount Gets the number of the pages required to display the reocrds of
the data source.

Pagelndex Gets or sets the 0-based page index.

Pagelndex Gets or sets the number of records to display in one page of


GridView.

Rows Gets a collection of GridViewRow objects that represents the


currently displayed rows in the GridView.

DatakeyNames Gets an array that contains the names of the primary key field of
the currently displayed rows in the GridView.

Datakeys Gets a collection of DataKey objects that represent the value of


the primary key fields set in DataKeyNames property of the
GridView.

Table 2.4 State Properties

Property name Description

PagelndexChanging, Both events occur when the page link is clicked. They fire before
PagelndexChanged and after GridView handles the paging operation respectively

RowCancelingEdit Fires when Cancel button is clicked in Edit mode of GridView.

RowCommand Fires when a button is clicked on any row of GridView.


Unit-2 Server Control

RowCreated Fires whena new row is created in GridView.

RowDataBound Fires when row is bound to the data in GridView.

RowDeleting, RowDeleted Both events fires when Delete button of a row is clicked. They

fire before and after GridView handles deleting operaton of the


row respectively.

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

RowUpdated fire before and after GridView control update operation


respectively.

Sorting, Sorted Both events fire when column header link is clicked. They fire
before and after the GridView handler the Sort operation
respectively.

Table 2.5 Events

Example:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

DataKeyNames="ID" DataSourcelD="AccessDataSource1"

AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">

<Columns>

<asp:BoundField DataField="1D" HeaderText="ID" ReadOnly="True"

SortExpression="ID"/>

<asp:BoundField DataField="sname" HeaderText="'sname"


SortExpression="sname"/>

sasp:BoundField DataField="gender" HeaderText="gender

SortExpression="gender" /
10 Unit-2Server Contral

asp:BoundField DataField="userld" HeaderText="userld"

SortExpression="userld" />

sasp:BoundField Datafield="Passwrd" HeaderText="Passwrd"

SortExpression="Passwrd" />

</Columns>

/asp:GridView

casp:Access Data Source ID="AccessDataSource1" runat="server"

DataFile=JApp_Data/StudentDB.accdb"

SelectCommand="SELECT FROM (StudDetails]"

DeleteCommand="DELETE FROM [StudDetails] WHERE ID=@ID"

Update Command ="UPDATE (StudDetails] SET

SNAME-@SNAME,GENDER=@GENDER, USERID=@USERID,PASSWRD=@PASSWRD

WHERE ID=@ID>

</asp:AccessDataSource

2.2.2 ListBox Control

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

be able to give the user many select options.

The <select/> HTML tag is used to implement it when it is rendered on the page. Combo box
is another name for it.

Property name Description

Rows No. of rows (items) can be set to display in the List.

SelectionMode Single or Multiple. If multiple, it alows user to select multiple


items from the list by holding Ctrl or Shift key.

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.

tems Gets the collection of items from 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.)

DataSourcelD 1D of the datasource component to provide data. (Only used


when you have any DataSource component on the page, like
SqIDataSource, AccessDataSource etc.)

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

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 OnSelectedlndexChanged method.

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.)

Table 2.6 Important Properties

Example:

/ Listbox 1

<asp:ListBox ID="ListBox1" runat="server"

<asp:Listltem Text="Red" Value="red"></asp:Listltem>

sasp:Listltem Text="Blue" Value="blue"></asp:Listitem>

<asp:Listltem Text="Green" Value="green"></asp:Listltem>

</asp:ListBox>

I/ Listbox 2
<asp:list Box ID="ListBox1" runat="Server"/

// Listbox 3

<asp:ListBox ID="ListBox2" runat="server" DataTextField="Name" DataValueField="ID"


Rows="8" SelectionMode="multiple"/>
Unit-2 Server Control 13

I/Listbox 4

<asp:ListBox ID="ListBox3" runat="server" DataTextField="Name" DataValueField="ID"


OnSelectedlndexChanged="GivePostBackResult" AutoPost Back="True"/>

2.2.3 DataList Control

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.

Datalist control contains different types of template fields those are

1) itemTemplate

2) AlternatingitemTemplate

3) HeaderTemplate

4) FooterTemplate

5) SeperatorTemplate

1) ItemTemplate: ItemTemplate defines how the each item is rendered from data source

collection.

2) AlternatingltemTemplate: AlternatingltemTemplates is used to change the background


color and styles of Alternatingltems in DataSource collection

3) HeaderTemplate: HeaderTemplate is used to display Header text for DataSource


collection and apply different styles for header text.

4) FooterTemplate: FaoterTemplate is used to display footer element for DataSource

collection.
14 Unit-2 Server Control

5) SeparatorTemplate: SeparatorTemplate will determine separator element which


separates each Item in Item collection. Usually, SeparateTemplate will be cbr> html element
or <hr> html element.

Format of Datalist control:

<asp: Datalist ID="Datalist1" runat="'server"

cHeaderTemplate>

/HeaderTemplate>

<ltemTemplate

</temTemplate>

<FooterTemplate>

</FooterTemplates

s/asp:Datalist>

Example:

<asp:Datalist ID="Datalist1" runat="server" DataKeyField="|ID"

DataSourcelD="SqIDataSource1">

cHeaderTemplate

Details

</HeaderTemplate

<FooterTemplate>

nd
Unit-2 Server Control

/FooterTemplate>

<ltemTemplate>

ID:

<asp:label 1D="IDLabel" runat="server" ForeColor= "#CC66FF"

Text= <%t Eval("ID") %>'/

<br/
name:

<asp:Label ID="namelabel" runat="server" ForeColor="#6600CC"

Text=<%# Eval("name") %>°'/>

<br/>

gender

<asp:label ID="genderlabel" runat="server"

Text=<% Eval("gender") 65'/>


<br/>

username:

<asp:Label ID="usernamelabel" runat="server"

Text='<%t Eval("'username") %>'/>

<br/>

password:

<asp:Label ID="passwardLabel" runat="server

Text=<%t Eval("password") %' />

<br/
<br/>

</ltemTemplate>

<Jasp:DataList>
16 Unit-2 Server Control

2.2.4 Data Binding Events:

The following two events can be used as data binding events:

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.

2.2.5 Repeater Control

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.

Repeater control contains different types of template fields those are

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.

2) AlternatingltemTemplate: AlternatingltemTemplates is used to change the background


color and styles of Alternatingltems in DataSource collection

3) HeaderTemplate: HeaderTemplate is used to display Header text for DataSource

collection and apply different styles for header text.

4) FooterTemplate: FooterTemplate is used to display footer element for DataSource


collection

5) SeparatorTemplate: SeparatorTemplate will determine separator element which


separates each Item in Item collection. Usually, SeparateTemplate will be <br> html element
or <hr> htrml element.

Format of Repeater control:

<asp:Repeater id="cdcatalog" runat="server"


<HeaderTemplate>

</HeaderTemplate
<ltemTemplate>

</ltemTemplate>
FooterTemplate

</FooterTemplate>
s/asp:Repeater

Example Repeater control:


18 Unit-2 Server Control

<asp:Repeater ID="rptCustomers" runat="server" DataSourcelD= "Sq!DataSource1">

<HeaderTemplate»

stable cellspacing="0" rules="all" border="1">

<tr

<th scope="col" style="width: 80px">

Id

</th>

<th scope="col" style="width: 120px">

Name

</th>

sth scope="col" style="width: 100px">

Gender

</th>

/tr>
</HeaderTemplate>

<ltemTemplate>

<tr>

<td>

<asp:Label ID="lblCustomerld" runat="server"

Text='<%# Eval("ld") %>>

</td>

<tds

<asp:label ID="IblContactName" runat="server"

Text=<%# Eval("Name") %>'/>

</td>
Unit-2 Server Control 19

<td
<asp:label lID="IblCountry" runat="server"

Text=<9%t Eval("Gender") %>'/>

</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

it for simple text data type.

2) ButtonField-Showing a Button control.

3) CheckBoxField - Showing a CheckBox control, used for boolean yes/no fields.

4) CommandField Command buttons, like Edit, Delete or New, used for manipulating
-

data.

5) HyperlLinkField - Used to show a hyperlink.

6) ImageField- Used to show an image

7) TemplateField Used to show data in custom layout, when other field types are
inadequate.

Example:
20 Unit-2 Server Control

<asp:DetailsView 1D = "DetailsView1" runat = "server" Height = "50px" Width = "125px"


AllowPaging = "True" DataSourcelD = "AccessData Source1" AutoGenerateRows = "False"
DatakeyNames = "ID">

<Fields>

<asp:BoundField DataField="ID" HeaderText="ID"

ReadOnly="True" SortExpression="ID" />

<asp:BoundField DataField= "sname" HeaderText="sname"


SortExpression="sname"/>

<asp:BoundField DataField="gender" HeaderText="gender"

SortExpression="gender"/>

<asp:BoundField DataField="userld" HeaderText="userld"

SortExpression="userld"/

<asp:BoundField DataField="Passwrd" HeaderText="Passwrd"

SortExpression="Passwrd"/>

/Fields>
s/asp:DetailsView>

2.2.6 FormView Control:

FormView Control is similar to DetailsView control.

Both controls enable showing of single record from data source.

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.

Unlike DetailsView, FormView control doesn't have predefined data layout.

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.

Templates available in FormView controls are:

HeaderTemplate

.ItemTemplate

InsertltemTemplate

EditltemTemplate

EmptyDataTemplate

PagerTemplate

FooterTemplate

Example:

<asp:FormView ID="FormView1" runat="server" AllowPaging="True"

DataKeyNames="ID" DataSourcelD= "AccessDataSource1"

<EditltemTemplate>

ID:

<asp:label ID="IDLabel1" runat="server" Text='<%# Eval("ID'") %>'/>

cbr/
sname:

<asp:TextBox ID="snameTextBox" runat="server" Text='<%# Bind("'sname") %> />

<br/
gender:

<asp:TextBox ID="genderText Box" runat="server" Text='<9%#t Bind("gender") %»'/>

cbr/>
userld:
22 Unit-2 Server Control

<asp:TextBox ID="userldTextBox" runat="server"

Text-'<%# Bind("userld") %>' />

br

Passwrd:

casp:TextBox ID="PasswrdTextBox" runat="server

Text-<%# Bind("Passwrd") %>'/>

<br/
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"

CommandName="Update" Text="Update" /

&nbspcasp:LinkButton ID="UpdateCancelButton" runat="'server

CausesValidation="False" CommandName="Cancel" Text="Cancel"/>

</EditltemTemplate

<lnsertltemTemplate

ID:

casp:TextBox ID="IDTextBox" runat="server" Text=<%# Bind("ID") 6>'/>


<br />

sname:

<asp:TextBox ID="snameTextBox" runat="server" Text='<%# Bind("sname") %>'/>>

<br />

gender:

<asp:TextBox ID="genderTextBox" runat="server"

Text<# Bind("gender") %'

<br/>

userld:

sasp:TextBox ID="userldTextBox" runat="server"


Unit-2 Server Contro

Text=<9%6# Bind('userld") %>'/>

<br/
asswrd:

<asp:TextBox ID="PasswrdTextBox" runat="server"

Text=<%# Bind("Passwrd") %>' />

<br />

<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"

CommandName="Insert" Text="Insert"/>

&nbsp<asp:LinkButton ID="InsertCancelButton" runat="server"

CausesValidation="False" CommandName="Cancel" Text="Cancel" />

</InsertitemTemplate

<ltemTemplate>

ID
<asp:label 1D="IDLabel" runat="server" Text=<96# Eval("ID") 6>/>

br

sname:

casp:Label ID="snamelabel" runat="server" Text='<%# Bind("sname") %>'/>

br,

gender:

<asp:label lD="genderlabel" runat="'server" Text=<%t# Bind("gender") %> />

<br/>

userld:

<asp:Label ID="userldlabel" runat="server" Text=<%6# Bind("userld") %>'/>

<br/>

Passwrd:
Unit-2 Server Control

<asp:label ID="PasswrdLabel" runat="server" Text=<%# Bind("Passwrd") 9%>"

<br/>

</ItemTemplate>

</asp:FormView>

2.3 Web Server Controls:

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.

Following are the server controls for the web forms:

Control Name Events Deseription


Label None Label control is used to display text on the
HTML page.
TextBox TextChanged It is used to create a text input in the form.
Button Click, Button control is used to create a button.
Command
|
LinkButton Click, It is will create a button which look same as
Command the hyperlink.
ImageButton Click
It
is used to create an imagesButton. Here, an
image works as a Button.
Hyperlink None It
is used to create a hyperlink control that
responds to a click event.
DropDown List SelectedindexChanged It
is used to create a dropdown list control.
DataGrid CancelCommand, It used to create a frid that is used to show
EditCommand, data. We can also perform paging, sorting,
DeleteCommand, and formatting very easily with this control.
ItemCommand,
SelectedindexChanged,
PagelndexChanged,
SortCommand,
UpdateCommand,
Unit-2 Server Control 25

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

HTML Server Controlss

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.

For example, consider the HTML input control:

sinput type="text" size="40">

It could be converted to a server control, by adding the runat and id attribute:

<input type="text" ld="testtext" size="40" runat="server">

Advantages of using HTML Server Controls


Although ASP.NET server controls can perform every job accomplished by the HTML server
controls, the later controls are useful in the following cases:

Using static tables for layout purposes.

Converting a HTML page to run under ASP.NET

Control Name HTML Tag

HtmlHead <head>element
HtmlInputButton <input type=button submit| reset>
HtmlinputCheckbox <input type=checkbox
HtmllinputFile cinput type = file>
HtmllnputHidden <input type = hidden>

Htmllnputimage input type = image>


HtmlInputPassword <input type = passwords

HtmlinputRadioButton input type = radio>


Htmllnput Reset sinput type = reset
HtmiText <input type = text|password>
Htmllmage Kimg> element
HtmlLink <link> element
HtmIAnchor <a> element

HtmlButton <button> element


HtmlButton <button> element
Unit-2 Server Control 27

HtmlForm form> element


HtmITable <table> element
HtmlTableCell <td> and <th>
HtmlTableRow <tr> element

HtmITitle <title> element


HtmiSelect <select&t; element
HtmlGenericControl HTML controls not listed
All
Table 2.8 HTML Server Controls

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)

Image 2.1 HTML Server Controls in ASP.NET

Validation Control

ASP.NET validation controls validate the user input data to ensure that useless,
unauthenticated, or contradictory data don't get stored.

Validation allows you to validate an input of the user.

If user enters values that do not match the validation criteria, you can show appropriate
message to the user.

ASP.NET provides the following validation controls:

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.

The syntax of the control is as given:

<asp:RequiredFieldValidator ID="ReqFvalName" runat="server"

ControlToValidate="txtName" ErrorMessage="Name is required">

</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

The syntax of the control is as given:

<asp:RangeValidator ID="RanValAge" runat="server" ControlToValidate="txtAge"


ErrorMessage="Age should be between 18 to 30" MaximumValue="30"
MinimumValue="18"

</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

Type It specifies the data type.


ControlToCompare It specifies ID of the control to compare
ControlToValidate It specifies ID of the control to validate
Operator It specifies the comparison operator, the available values are: Equal,

NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual,


and DataTypeCheck.

Table 2.10 Properties of CompareValidator Control

The basic syntax of the control is as follows:

<asp:CompareValidator ID="ComVal ConPasswd" runat-"server"

ControlTovValidate="txtConfirmPasswd" ErrorMessage="Password are not same"

ControlToCompare="txt Password">

</asp:Comparevalidator

RegularExpressionValidator Control

The RegularExpressionValidator allows validating the input text by matching against a


pattern of a regular expression. The regular expression is set in the ValidationExpression
property.

The following table summarizes the commonly used syntax constructs for regular
expressions:

Character Escapes Description


Matches a backspace.
Matches a tab.

Matches a carriage return.

Matches a vertical tab.


Matches a form feed.

\n Matches a new line.


Escape character.

Table 2.11 Character Escapes for regular expressions


30 Unit-2 Server Control

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.

abcd Matches any character in the set.


abcd Excludes any character in the set.
(2-7a-mA-M] Matches any character specified in the range.
\W Matches any alphanumeric character and
underscore.
\W Matches any non-word character.
Is Matches whitespace characters like, space, tab,
new line etc.
\d Matches any decimal character.
\D Matches any non-decimal character.

Table 2.12 Metacharacters for regular expressions

Quantifiers could be added to s ify number of times a character could appear.

Quantifier Description
Zero or more matches.
One or more matches.

Zero or one matches.

IN N matches.
N,} N or more matches.
N,M} Between N and M matches.

Table 2.13 Quantifier for regular expressions

The syntax of the control is as given:

<asp:RegularExpressionValidator ID="RegExValEmail" runat="server"


ControlToValidate="txtEmail" ErrorMessage="Email format: [email protected]"

ValidationExpression="\w+{l+:]\w+)*@\w+(-J\w+}*\w+{[-Jw+)*"

</asp:RegularExpressionValidator>
Unit-2 Server Control 31

Regular Expression for Mobile Number:

[2-9]1210-9]18}S

Here (carat) matches at the start of the line.

$(dollar) is the end of line ancho.

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.

2-9 is the range of number.

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.

Example for the control is as given:

protected void CusValUserld_ServerValidate(object source, ServerValidateEventArgs args)

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:

Showsummary: shows the error messages in specified format.

ShowMessageBox: shows the error messages in a separate window.

The syntax for the control is as given:

<asp:ValidationSummary ID="ValidationSummary1" runat="server" />

Navigation Control

Navigation controls are basically used to navigate the user from one page to other.

It is more helpful for making the navigation of pages easier.

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.

1. TreeView Node Editor dialog box

2. Generate TreeView based on XML Data

3. Generate TreeView based on Web.SiteMap data

4. Generate TreeView from Database.


Unit-2 Server 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

Image 2.2 TreeView Control

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

the TreeView control.


NodeStyle It allows you to set the default appearance of the nodes in
the TreeView control.
RootNodeStyle It allows you to set the appearance of the root node in
the TreeView control.
SelectedNode Gets a TreeNode object that represents the selected node in
the Treeview control.
SelectedNodeStyle Gets the TreeNodeStyle object that controls the appearance of the
selected node in the TreeView control.
SelectedValue Gets the value of the selected node.

Table 2.14 Notable Properties

Event Description
TreeNodeCheckChanged Fired after the check state of node changed

Table 2.15 Notable Events

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).

Items It gets a Menultem Collection of object that contains all


menu items.
Selecteditem |
It gets the selected menu item.
SelectedValue It gets the value of the selected menu item.
Pathseparator It gets or set the character that is used as separator for the
item.
Style It gets a collection of text attribute that will be rendered as a
style attribute of the Web server control
Table 2.16 Properties of Menu Control

Event Description
MenultemClick{) Fired after an item has been clicked

Table 2.17 Notable Event

SeriotManaaer SeripthManagerl
BspiiehuacndL
Hame ogin adminhomeHaw 1tem

Image 2.3 Menu Control

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.

You can bind this control to TreeView and Menu controls.


Unit-2 Server Control 35

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.

BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height, and other properties


are implemented using the style properties of the <table, tr, and td/> tags.

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.

CreateUserUrl Indicates the url of the create user page.


CreateUserText Indicates the text of the create user link.
36 Unit-2 Server Contro

PasswordRecoveryUrl Indicates the url of the password recovery page.


PasswordRecoveryText Indicates the text of the password recovery link.
Table 2.19 Properties of Login Control

Properties Description

CheckBoxStyle Indicates the style property of the Remember Me checkbox.

FailureStyle Indicates the style property of the failure text.

TitleTextStyle Indicates the style property of the title text.

LoginButtonStyle Indicates the style property of the Login button.

TextBoxStyle Indicates the style property of the TextBox.

LabelStyle Indicates the style property of the labels of text box.

HyperlLinkstyle Indicates the style property of the hyperlink in the control.

InstructionTextStyle Indicates the style property of the Instruction text that


appears below the heading of the control.

Table 2.20 Style Properties of Login Control

Properties Description

Loggingln Fires before user is going to authenticate.

Loggedin Fires after user is authenticated.

LoginError Fires after failure of login attempt.

Authenticate Fires to authenticate the user. This is the function where you

need to write your own code to validate the user.


Unit-2 Server Control

Table 2.21 Events of the Login Control

Example:

<asp:Login 1D="Login1" runat="server" BackColor="#F7F6F3" BorderColor="#E6E2D8"


BorderPadding="4"

BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em"

ForeColor="#333333" OnAuthenticate="Login1_Authenticate"
OnLoginError="Login1_LoginError">

<TitleTextStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.9em"


ForeColor="White"/>

cinstructionTextStyle Font-Italic="True" ForeColor="Black" />

TextBoxStyle Font-Size="o.8em"/>

cLoginButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCcc" BorderStyle="Solid"


BorderWidth="1px"

Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284775" />

</asp:Login>

Log In

User Name:

Password:

Remember me next time.

Log In

Register User
Forget password?

Image 2.4 Login Control


38 Unit-2 Server Control

2.4 Master Page

Creating the Master Page:

It allows you to create a consistent layout for the pages in your application.

Following are the steps to embed master page in your application

1. Right click on solution explorer of your website.

2. Select Add new item.

3. Select Master Page option from Add new item Dialog Box.

4. Change name of Master Page.

5. Click on Add button.

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.

E.g Menu control from Navigation, Image, Heading, Footer etc.

7. Perform necessary Design steps and save the Master Page.

Implementing the Master Page on Web Form

There are 2 ways to implement master page

1:Selection of master page directlyfrom Dialog Box


1. Right click on solution explorer of your website.

2. Select Add new item and select web form.

3. Give Proper name to the web form and Check Select master page option at

bottom right of the Dialog Box.


Unit-2 Server Control 39

Add Nerw hem cRahuinehTestprojectsmaterPae Test,

Veual Sudo inetaled templotes

t 1webthe Cortrd
**

soe s
e we
Cre te web Carhgn

Clan ag
y femeletr

Afam fo ob kccek

Nane: te.p

Lga

Image 2.5 Create Master Page

4. Click on Add button.

S. Select Master page dialog box will get open

Select a Master Pags

Erotfokbersr
8anePaetet Msterfageore.nastr

Image 2.6 Select Master Page

6. Select name of the Master Page You want to use.

7. Now add contents to ContentPlaceHolder.

2:Selection of master page directly from Dialog Box


1. Write following code at the first line of aspx page. (In Page Directive)

MasterPageFile="-/MasterPage.master"
40 Unit-2 Server Control

(%@Page Language="C#" MasterPagefile="-/MasterPage.master"


AutoEventWireup="true'" CodeFile="Registration.aspx.cs"
Inherits="Registration "%>)

2. Delete all other code lines from .aspx page.

3. Write below code:

<asp:Content ContentPlaceHolderlD="ContentPlaceHolder1"
runat="server"></asp:Content>

ent Objects & Events (No Events)

Page Language="ck" AutcžventNizeup="true" CodeFile="Default3.aapx.cs" Inkerits="Default3


MasterFageFile"-/NasterFage.zaster"

Kasp:Content io="Contenti" zurats"ervez" concentplaceholderid="ContentFlaceRolder1"

-</asp:Centent>

Image 2.7 Master Page

OR

You can directly go to design section of .aspx page and from contentPlaceHolder select

"Create Custom Content".

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 applies to any Server control.

It is used to set Height, width, Forecolor, backcolor, bordercolor of any asp.net server
controls.
Unit-2 Server Contro

Steps to create Skinfile:

1. Right click on solution explorer.

2. Select Add new item-> Select SkinFile from dialog Box.

3. Change name if you want and click on Add button.

4. Alert will ask to add Skinfile in ApP_Themes folder. Click Yes button.

5. Add name of controls you want to provide effects.

Example:

<asp:TextBox runat-"server" Backcolor="yellow" BorderColor="Blue"> </asp:TextBox>

<asp:label runat-"server" Forecolor-"Pink"> </asp:Label>

APply theme (SkinFile) to page

There are two ways to Apply Theme to your web form

1. Add Theme Attribute inside @page Directive Theme="Skin File"

(%@Page Language="CH" MasterPageFile="/MasterPage.master"


AutoEventWireup="true" CodeFile="Registration.aspx.cs" Inherits="Registration"
Theme="SkinFile"9%>)

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

matched exactly by control type, so that a Button control skin applies to


all Button controls, but not to LinkButton controls or to controls that derive from
the Button object.)
42 Unit-2 Server Control

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.

cSs( Cascading Style Sheets)

cSS Stands for Cascading Style Sheets.

It applies on any HTML Controls. It provides consistent appearance throughout your


website.

Creating a CcSS Style Sheet

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

Solution BlogExampleCSharp' (1 project)


Cajb web\BlogExampleCSharpl
Build Web Site naster

Publish Web Site


New Item.. Ctrl+Shift
Ckia. Au. A

Image 2.8 Right-click, as ever, on your project in Solution Explorer and choose to add a new

item

Now choose to create a style sheet:


Unit-2 Server Control 45

TM

Image 2.9 Choose style sheet

The steps to follow are:

1. Choose to create a style sheet.

2. Give your style sheet a name (often calling it after the website works well).

3. Click on the button to add your style sheet to the website.

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

mage 2.10 Example of css style

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

Add Style Rule..

Synchronize Document Outline

Image 2.11 Build Style

Applying a Style Sheet to a page

To apply a style sheet to any page:

1. Open the page for editing in Design view (here we're using the master page).

2. Select the style sheet you want to apply.

3. Drag it onto the page and release the mouse button.

Here are the numbered stages described above:

BlogExamnle.master Solution Explorer


www

To-do list website Solution BlogExampleCSharp'


Cajb web\BlogExamgleCs
A BlogExample.cs

O BlogExample.master
Default.aspx
web.config

Image 2.12 Applying a Style sheet

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

<html xmlns- "http:/lmad.M3.org/1999/xhtm]">


chead runat=""server"
titleTo-do list</title>
</head>
klink href="81ogExample.css" rel-"stylesheet" type-"text/css" /
cbody>
<fcid="form1" runat-"server">

Applying a style sheet to a page can have a fairly dramatic effect:

BlogExample.masterXI
|BlogExample.master Xx
UUUyy.
bodyl
To-do list website
To-do ist website

Before and after


Image 2.13 After applying stylesheet

Difference between cSS and Themes

CSS:

1. Applies to all HTML Controls

2. Is applied on the Client Side in the Browser

3. We can apply multiple style sheets to a single page

4. The CSS supports cascading

5. The CSS cannot override the property values defined for a control.

6. Cannot be applied through the configuration files

7. Can be used directly via a reference to the css file location

8. Do not require any other resource like Skin files

9. In case of CSS you can define only style properties

Themes:
46 Unit-2 Server Contral

1. Applies to all the server controls

2. Is applied on the server rather than in the browser

3. But we cannot apply multiple themes to a single page. Only one theme we can

apply for a single page.

4. But themes does not support cascading

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.

6. Can be applied through Configuration Files.

7. All theme and Skin files should be placed in a special Asp.net folder called the

"ApP_Themes in order for the themes to work and behave normally.

8. Each theme should be associated with at least one Skin file.

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

Q-1 What is Server Control?

Q-2 Explain Postback in detall.


Q-3 What are Data Binding controls? Explain with example.
Q-4 What is the use of Detailsview Control. Explain with example.

Q-5 Explain Web Server Controls.

You might also like