+ All Categories
Home > Documents > Ch3 server controls

Ch3 server controls

Date post: 18-Jan-2015
Category:
Upload: madhuri-kavade
View: 3,080 times
Download: 0 times
Share this document with a friend
Description:
 
Popular Tags:
60
SERVER CONTROLS Types of Server Controls, HTML Server Controls, Web Controls, List Controls, Input Validation Controls, Rich Controls
Transcript
Page 1: Ch3 server controls

SERVER CONTROLS

Types of Server Controls, HTML Server Controls, Web Controls, List Controls, Input Validation Controls, Rich Controls

Page 2: Ch3 server controls

2

ASP.NET server controls are a fundamental part of the ASP.NET architecture.

Server controls are classes in the .NET Framework that represent visual elements on a web form

Some of these classes are relatively straightforward and map closely to a specific HTML tag.

Other controls are much more ambitious abstractions that render a more complex representation

SERVER CONTROLS

Page 3: Ch3 server controls

3

ASP.NET offers many different server controls.HTML server controls:

Classes that wrap the standard HTML elements.

Two examples include HtmlAnchor (for the <a> tag) and HtmlSelect (for the <select> tag)

Can turn any HTML tag into a server control

If there isn’t a direct corresponding class, ASP.NET will simply use the HtmlGenericControl class. simply add the runat="server" attribute to turn into server control

TYPES OF SERVER CONTROLS

Page 4: Ch3 server controls

4

Web controls: Duplicate the functionalities of the basic HTML elements

But have a more consistent and meaningful set of properties and methods that make it easier for the developer to declare and access them

Some examples are the HyperLink, ListBox, and Button controls.

More special types of web controls are also available.

TYPES OF SERVER CONTROLS CONT…

Page 5: Ch3 server controls

5

Rich controls:

Advanced controls have the ability to generate a large amount of HTML markup and even client-side JavaScript to create the interface.

Examples include the Calendar, AdRotator, and TreeView controls.

TYPES OF SERVER CONTROLS CONT…

Page 6: Ch3 server controls

6

Validation controls: Set of controls allows you to easily validate an associated input control against several standard or user-defined rules.

Can specify that the input can’t be empty, that it must be a number

If validation fails, you can prevent page processing or allow these controls to show inline error messages in the page.

TYPES OF SERVER CONTROLS CONT…

Page 7: Ch3 server controls

7

Data controls Include sophisticated grids and lists that are designed to display large amounts of data, with support for advanced features such as editing, sorting.

Includes the data source controls that allow you to bind to

different data sources declaratively, without writing extra code.

TYPES OF SERVER CONTROLS CONT…

Page 8: Ch3 server controls

8

Navigation controls

Designed to display site maps and allow the user to navigate from one page to another.

Login controls

Support forms authentication, an ASP.NET model for authenticating users against a database and tracking their status

Can use these controls to get prebuilt, customizable login pages, password recovery, and user-creation wizards.

TYPES OF SERVER CONTROLS CONT…

Page 9: Ch3 server controls

9

Web parts controls

ASP.NET model for building componentized, highly configurable web portals.

ASP.NET AJAX controls

Allow you to use Ajax techniques in your web pages without forcing you to write client-side code

Ajax-style pages can be more responsive because they bypass the regular postback-and-refresh page cycle.

TYPES OF SERVER CONTROLS CONT…

Page 10: Ch3 server controls

10

ASP.NET mobile controls Set of controls that resembles the web controls but is customized to support mobile clients such as PDAs, smart phones, and so on

Renders pages to markup standards such as HTML 3.2 or WML 1.1.

TYPES OF SERVER CONTROLS CONT…

Page 11: Ch3 server controls

11

All server controls derive from the base Control class in the System.Web.UI namespace.

THE SERVER CONTROL HIERARCHY

Page 12: Ch3 server controls

12

Most commonly used members of the Control classProperty Description

ClientID Identifier of the controlControls Returns the collection of child controlsEnableViewState Returns or sets a Boolean value related to view

state of control

ID Returns or sets the identifier of the controlPage Returns a reference to the page object that

contains the control

Parent Returns a reference to the control’s parentVisible Returns or sets a Boolean value indicating whether

the control should be Rendered

THE SERVER CONTROL HIERARCHY CONT…

Page 13: Ch3 server controls

13

Defined in the namespace System.Web.UI.HtmlControls

HTML SERVER CONTROL

Page 14: Ch3 server controls

14

HTML server controls on the page is the same as what you use for normal static HTML tags, with the addition of the runat="server“ attribute.

Complete this slide – page 120

Tag Declaration .NET Class Specific Members

<a runat="server">

HtmlAnchor HRef, Target, Title,Name, ServerClick event

<button runat="server">

HtmlButton CausesValidation,ValidationGroup,ServerClick event

<form runat="server">

HtmlForm Enctype, Method, Target,DefaultButton,DefaultFocus

<img runat="server">

HtmlImage Align, Alt, Border, Height,Src, Width

THE HTML SERVER CONTROL CLASSES

Page 15: Ch3 server controls

15

Tag Declaration

.NET Class Specific Members

<input type="button" runat="server">

HtmlInputButton Type, Value,CausesValidation,ValidationGroup,ServerClick event

<input type="reset" runat="server">

HtmlInputReset Type, Value

<input type="submit" runat="server">

HtmlInputSubmit Type, Value, CausesValidation,ValidationGroup, ServerClick event

<input type="checkbox" runat="server">

HtmlInputCheckBox Checked, Type, Value,ServerClick event

HTML SERVER CONTROL CLASSES

Page 16: Ch3 server controls

16

Tag Declaration

.NET Class Specific Members

<input type="file" runat="server">

HtmlInputFile Accept, MaxLength,PostedFile, Size, Type,Value

<input type="hidden" runat="server">

HtmlInputHidden Type, Value,ServerChange event

<input type="image" runat="server">

HtmlInputImage Align, Alt, Border,Src, Type, Value,CausesValidation,ValidationGroup,ServerClick event

<input type="radio" runat="server">

HtmlInputRadioButton Checked, Type, Value,ServerChange event

THE HTML SERVER CONTROL CLASSES

Page 17: Ch3 server controls

17

Tag Declaration

.NET Class Specific Members

<input type="text" runat="server">

HtmlInputText MaxLength, Type, Value,ServerChange event

<input type="password" runat="server">

HtmlInputPassword MaxLength, Type, Value,ServerChange event

<select runat="server">

HtmlSelect Multiple, SelectedIndex,Size, Value, DataSource,DataTextField,DataValueField, Items(collection),ServerChange event

<table runat="server">,<td runat="server">

HtmlTable Align, BgColor, Border,BorderColor,CellPadding,CellSpacing, Height,NoWrap, Width, Rows(collection)

THE HTML SEVER CONTROL CLASSES

Page 18: Ch3 server controls

18

Tag Declaration

.NET Class Specific Members

<th runat="server">

HtmlTableCell Align, BgColor, Border,BorderColor, ColSpan,Height, NoWrap,RowSpan, VAlign, Width

<tr runat="server">

HtmlTableRow Align, BgColor, Border,BorderColor, Height,VAlign, Cells (collection)

<textarea runat="server">

HtmlTextArea Cols, Rows, Value,ServerChange event

Any other HTML tag with therunat="server" attribute

HtmlGenericControl None

HTML SERVER CONTROL CLASSES

Page 19: Ch3 server controls

19

Can configure a standard HtmlInputText control

To read or set the current text in the text box, you use the Value property.

SETTING STYLE ATTRIBUTE AND OTHER PROPERTIES

Page 20: Ch3 server controls

20

Sometimes you don’t know in advance how many text boxes, radio buttons, table rows, or other controls

because this might depend on other factors such as the number of records stored in a database or the user’s input.

With ASP.NET, the solution is easy.

Can simply create instances of the HTML server controls you need, set their properties with the object-oriented approach

PROGRAMMATICALLY CREATING CONTROLS

Page 21: Ch3 server controls

21

HTML server controls provide a sparse event model with two possible events: ServerClick and ServerChange.

The ServerClick event is simply a click that is processed on the server side

The ServerChange event responds when a change has been made to a text or selection control

HANDLING SERVER-SIDE EVENTS

Page 22: Ch3 server controls

22

Event Controls That Provide It

ServerClick HtmlAnchor, HtmlButton, HtmlInputButton, HtmlInputSubmit,HtmlInputReset, HtmlInputImage

ServerChange

HtmlInputText, HtmlInputCheckBox, HtmlInputRadioButton, HtmlInputHidden, HtmlSelect, HtmlTextArea

HTML Control Events

HANDLING SERVER-SIDE EVENTS CONT…

Page 23: Ch3 server controls

23

Portion of the Inheritance Hierarchy for Web Controls

WEB CONTROLS

Page 24: Ch3 server controls

24

HTML server controls provide a relatively fast way to migrate to ASP.NET

ASP.NET provides a higher-level web control model

web controls are defined in the System.Web.UI.WebControls namespace

Web controls also enable additional features, such as automatic postback

Extended controls don’t just map a single HTML tag but instead generate more complex output made up of several HTML tags and JavaScript code

WEB CONTROLS CONT…

Page 25: Ch3 server controls

25

All the web controls inherit from the WebControl class.

The WebControl class also derives from Control.

WEB CONTROL CLASS PROPERTIES

Page 26: Ch3 server controls

26

Property Description

AccessKey Returns or sets the keyboard shortcut that allows the user to quickly navigate to the control.

BackColor Returns or sets the background color

BorderColor

Returns or sets the border color

BorderStyle

One of the values from the BorderStyle enumeration, including Dashed, Dotted, Double, Groove, Ridge, Inset, Outset, Solid, and None.

WEB CONTROL CLASS PROPERTIES…

Page 27: Ch3 server controls

27

Property DescriptionBorderWidth

Returns or sets the border width.

CssClass Returns or sets the CSS style to associate with the control. The CSS style can be defined in a <style> section at the top of the page or in a separate CSS file referenced by the page.

Enabled Returns or sets the control’s enabled state. If false, the control is usually rendered grayed out and is not usable.

Font Returns an object with all the style information of the font used for the control’s text.

WEB CONTROL CLASS PROPERTIES…

Page 28: Ch3 server controls

28

Property DescriptionForeColor Returns or sets the foreground color.

Height Returns or sets the control’s height.

TabIndex A number that allows you to control the tab order. This property is supported only in Internet Explorer 4.0 and higher.

Tooltip Displays a text message when the user hovers the mouse above the control. Many older browsers don’t support this property.

Width Returns or sets the control’s width.

WEB CONTROL PROPERTIES

Page 29: Ch3 server controls

29

ASP.NET Generated HTML Key Members

<asp:Button> <input type="submit"/> or<input type="button"/>

Text, CausesValidation, PostBackUrl,ValidationGroup, Click event

<asp:CheckBox>

<input type="checkbox"/>

AutoPostBack, Checked, Text, TextAlign, CheckedChanged event

<asp:FileUpload>

<input type="file"> FileBytes, FileContent, FileName,HasFile, PostedFile, SaveAs()

<asp:HiddenField>

<input type="hidden">

Value

BASIC WEB CONTROL CLASSES

Page 30: Ch3 server controls

30

ASP.NET Generated HTML

Key Members

<asp:HyperLink>

<a>...</a> ImageUrl, NavigateUrl, Target, Text

<asp:Image> <img/> AlternateText, ImageAlign, ImageUrl

<asp:ImageButton>

<input type="image"/>

CausesValidation, ValidationGroup,Click event

<asp:ImageMap>

<map> HotSpotMode, HotSpots (collection),AlternateText, ImageAlign, ImageUrl

BASIC WEB CONTROL CLASSES

Page 31: Ch3 server controls

31

ASP.NET Generated HTML Key Members

<asp:Label> <span>...</span> Text, AssociatedControlID

<asp:LinkButton> <a><img/></a> Text, CausesValidation, Validation-Group, Click event

<asp:Panel> <div>...</div> BackImageUrl, DefaultButton,GroupingText, HorizontalAlign,Scrollbars, Wrap

<asp:RadioButton>

<input type="radio"/>

AutoPostBack, Checked, GroupName,Text, TextAlign, CheckedChanged event

BASIC WEB CONTROL CLASSES

Page 32: Ch3 server controls

32

ASP.NET Generated HTML Key Members

<asp:Table> <table>...</table> BackImageUrl, CellPadding,CellSpacing, GridLines,HorizontalAlign, Rows (collection)

<asp:TableCell>

<td>...</td> ColumnSpan, HorizontalAlign,RowSpan, Text, VerticalAlign, Wrap

<asp:TableRow>

<tr>...</tr> Cells (collection), HorizontalAlign,VerticalAlign

<asp:TextBox>

<input type="text"/> or<textarea>...</textarea>

AutoPostBack, Columns, MaxLength, ReadOnly, Rows, Text, TextMode, Wrap, TextChanged event

BASIC WEB CONTROL CLASSES

Page 33: Ch3 server controls

33

<asp:TextBox runat="server" ID="TextBox1" Text="This is a test” ForeColor="red" BackColor="lightyellow" Width="250px”Font-Name="Verdana" Font-Bold="True" Font-Size="20" />

Differences:

• The control is declared using its class name (TextBox) instead of the HTML tag name (input).

• The default content is set with the Text property, instead of a less obvious Value attribute.

• The style attributes (colors, width, and font) are set by direct properties, instead of being grouped together in a single style attribute.

BASIC WEB CONTROL CLASSES

Page 34: Ch3 server controls

34

Enumerations: Enumerations are used heavily in the .NET class library Used to group a set of related constants. For example, can set a control’s BorderStyle property, you can choose one of several predefined values from the BorderStyle enumeration

ctrl.BorderStyle = BorderStyle.Dashed;

In the .aspx file, set an enumeration by specifying one of the allowed values as a string (don’t include the name of the enumeration type)

<asp:TextBox BorderStyle="Dashed" Text="Border Test" id="txt” runat="server" />

BASIC WEB CONTROL CLASSES

Page 35: Ch3 server controls

35

Colors: Color property refers to a Color object (System.Drawing namespace) Can create Color objects in several ways:

• Using an ARGB (alpha, red, green, blue) color value: specify each value as integer.

// Create a color from an ARGB value.

int alpha = 255, red = 0, green = 255, blue = 0;

ctrl.ForeColor = Color.FromArgb(alpha, red, green, blue);

• Using a predefined .NET color name: choose the correspondingly named read-only property from the Color class

// Create a color using a .NET name.

ctrl.ForeColor = Color.Blue;

• Using an HTML color name: You specify this value as a string using the ColorTranslator class.

// Create a color from an HTML code.

ctrl.ForeColor = ColorTranslator.FromHtml("Blue");

BASIC WEB CONTROL CLASSES

Page 36: Ch3 server controls

36

The Default Button:

ASP.NET includes a mechanism that allows you to designate a default button on a web page.

The default button is the button that is “clicked” when the user presses the Enter key.

<form id="Form1" DefaultButton="cmdSubmit"

runat="server“>

BASIC WEB CONTROL CLASSES

Page 37: Ch3 server controls

37

Scrollable Panels:

The Panel control has the ability to scroll.

The panel is rendered as a <div> tag.

BASIC WEB CONTROL CLASSES

Page 38: Ch3 server controls

38

Server-side events work in much the same way as the server events of the HTML server controls.

Web controls support the AutoPostBack feature.

Example application adds a new entry to a list control every time one of the events occurs

HANDLING WEB CONTROL EVENTS

Page 39: Ch3 server controls

39

The list controls are specialized web controls that generate list boxes, drop-down lists, and other repeating controls.

Can be either bound to a data source

Allow the user to select one or more items

THE LIST CONTROLS

Page 40: Ch3 server controls

40

Control Description

<asp:DropDownList>

A drop-down list populated by a collection of <asp:ListItem> objects.In HTML, it is rendered by a <select> tag with the size="1" attribute.

<asp:ListBox>A list box list populated by a collection of <asp:ListItem> objects. In HTML, it is rendered by a <select> tag with the size="x" attribute, where x is the number of visible items.

<asp:CheckBoxList>

Its items are rendered as check boxes.

<asp:RadioButtonList>

Like the <asp:CheckBoxList>, but the items are rendered as radiobuttons.

<asp:BulletedList>

A static bulleted or numbered list. In HTML, it is rendered using the <ul> or <ol> tags( Can use to create list of hyperlinks).

THE LIST CONTROLS CONT..

Page 41: Ch3 server controls

41

The selectable list controls include the DropDownList, ListBox, CheckBoxList, and RadioButtonList controls.

RadioButtonList and CheckBoxList render multiple option buttons or check Boxes.

THE SELECTABLE LIST CONTROLS

Page 42: Ch3 server controls

42

The BulletedList control is the server-side equivalent of the <ul> (unordered list) or <ol>

Property DescriptionBulletStyle Determines the type of list

BulletImageUrl If the BulletStyle is set to CustomImage, this points to the image.

FirstBulletNumber

this sets the first value

DisplayMode Determines whether the text of each item is rendered as text or a hyperlink

THE BULLETED LIST CONTROLS

Page 43: Ch3 server controls

43

Validation Control Description

<asp:RequiredFieldValidator>

Checks that the control to validate is not empty.

<asp:RangeValidator>

Checks that the value of the associated control is within a

specified range

<asp:CompareValidator>

Checks that the value of the associated control matches a

specified comparison

<asp:RegularExpressionValidator>

Checks if the value of the control it has to validate matches

the specified regular expression

<asp:CustomValidator>

Allows you to specify any client-side JavaScript validation

routine and its server-side counterpart for validataion

<asp:ValidationSummary>

Shows a summary with the error messages for each failed

validator on the page

INPUT VALIDATION CONTROLS

Page 44: Ch3 server controls

44

What happens when the user clicks the button depends on the value of the CausesValidation property.

CausesValidation is false: ASP.NET will ignore the validation controls.

CausesValidation is true (the default): ASP.NET will automatically validate the page when the user clicks the button.

VALIDATION PROCESS

Page 45: Ch3 server controls

45

BaseValidator Members:

ControlToValidate Display

EnableClientScript Enabled

ErrorMessage Text

IsValid SetFocusOnError

ValidationGroup Validate()

The validation control classes are found in the System.Web.UI.WebControls namespace and inherit from the BaseValidator class.

THE BASIC VALIDATOR CLASS

Page 46: Ch3 server controls

46

The simplest available control is RequiredFieldValidator.

Ensures that the associated control is not empty.

Simple Example:

<asp:TextBox runat="server" ID="Name" />

<asp:RequiredFieldValidator runat="server"

ControlToValidate="Name" ErrorMessage="Name is required” Display="dynamic">*

</asp:RequiredFieldValidator>

REQUIRED FIELD VALIDATOR CONTROL

Page 47: Ch3 server controls

47

The RangeValidator control verifies that an input value falls within a predetermined range. The MinimumValue and MaximumValue properties define an inclusive range of valid values Example: <asp:TextBox runat="server" ID="DayOff" /><asp:RangeValidator runat="server" Display="dynamic"ControlToValidate="DayOff" Type="Date"ErrorMessage="Day Off is not within the valid interval"MinimumValue="08/05/2008"

MaximumValue="08/20/2008">*</asp:RangeValidator>

RANGE VALIDATOR CONTROL

Page 48: Ch3 server controls

48

The CompareValidator control compares a value in one control with a fixed value or, more commonly, a value in another control.Operator property allows you to specify the type of comparison you want to do(Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck). The DataTypeCheck value forces the validation control to check that the input has the required data type.

<asp:TextBox runat="server" ID="Age" />

<asp:CompareValidator runat="server" Display="dynamic"

ControlToValidate="Age" ValueToCompare="18"

ErrorMessage="You must be at least 18 years old"

Type="Integer" Operator="GreaterThanEqual">*

</asp:CompareValidator>

COMPARE VALIDATOR CONTROL

Page 49: Ch3 server controls

49

The RegularExpressionValidator control is a powerful tool in the ASP.NET developer’s toolbox. allows you to validate text by matching against a pattern defined in a regular expressionRegular expressions are also powerful tools—they allow you to specify complex rules.

<asp:TextBox runat="server" ID="Email" />

<asp:RegularExpressionValidator runat="server"

ControlToValidate="Email" ValidationExpression=".*@.{2,}\..{2,}"

ErrorMessage="E-mail is not in a valid format" Display="dynamic">*

</asp:RegularExpressionValidator>

REGULAR EXPRESSION VALIDATOR

Page 50: Ch3 server controls

50

Character Escapes

Description

Ordinary characters

Characters other than .$^{[(|)*+?\ match themselves

\b Matches a backspace

\t Matches a tab

\r Matches a carriage return

\v Matches a vertical tab.

\f Matches a form feed

\n Matches a newline

\ If followed by a special character (one of .$^{[(|)*+?\), this character escape matches that character literal.

REGULAR EXPRESSION VALIDATOR

Page 51: Ch3 server controls

51

Character Class Description

. Matches any character except \n.

[aeiou] Matches any single character specified in the set.

[^aeiou] Matches any character not specified in the set.

[3-7a-dA-D] Matches any character specified in the specified ranges (in the example the ranges are 3–7, a–d, A–D).

\w Matches any word character; that is, any alphanumeric character or the underscore (_).

\W Matches any non-word character

\s Matches any whitespace character (space, tab, form feed, newline, carriage return, or vertical feed).

\S Matches any non-whitespace character.

\d Matches any decimal character.

\D Matches any non-decimal character

REGULAR EXPRESSION VALIDATOR

Page 52: Ch3 server controls

52

Quantifiers

Quantifier

Quantifier Description

* Zero or more matches

+ One or more matches

? Zero or one matches

{N} N matches

{N,} N or more matches

{N,M} Between N and M matches (inclusive

REGULAR EXPRESSION VALIDATOR

Page 53: Ch3 server controls

53

Commonly Used Regular Expressions

Content Regular Expression Description

E-mail address \S+@\S+\.\S+ Defines an email address that requires anat symbol (@) and a dot (.), and only allows nonwhitespace characters.

Password \w+ Defines a password that allows anysequence of word characters

Specific-length password

\w{4,10} Defines a password that must be at leastfour characters long but no longer than ten Characters

Advanced password

[a-zA-Z]\w{3,9} Defines a password that allows four to ten total characters, as with the specific-length password. The twist is that the first character must fall in the range of a–z or A–Z (that is to say, it must start with a nonaccented ordinary letter).

REGULAR EXPRESSION

Page 54: Ch3 server controls

54

Commonly Used Regular ExpressionsContent Regular Expression Description

Another advanced password

[a-zA-Z]\w*\d+\w* Defines a password that starts with a letter character, followed by zero or more word characters, one or more digits, and then zero or more word characters. In short, it forces a password to contain a number somewhere inside it. You could use asimilar pattern to require two numbers or any other special character.

Limited-length field

\S{4,10} Defines a string of four to ten characters(like the password example), but it allowsspecial characters (asterisks, ampersands,and so on).

REGULAR EXPRESSION VALIDATOR

Page 55: Ch3 server controls

55

Commonly Used Regular Expressions

Content Regular Expression Description

Social Security number (US)

\d{3}-\d{2}-\d{4} Defines a sequence of three, two, and thenfour digits, with each group separated by ahyphen. A similar pattern could be usedwhen requiring a phone number.

Page 56: Ch3 server controls

56

The ValidationSummary control doesn’t perform any validation

it allows you to show a summary of all the errors in the page

summary displays the ErrorMessage value of each failed validator

ShowMessageBox and ShowSummary Properties

VALIDATION SUMMARY

Page 57: Ch3 server controls

RICH WEB SERVER CONTROLS Rich controls provide an object model

that has a complex HTML representation and

also client side JavaScript.

Examples:- AdRotator

Calendar

Page 58: Ch3 server controls

ADROTATOR CONTROL

Steps for using AdRotator

Define the XML schedule file with <Ad> tag and its properties defined

Specify Advertisement file value un AdRotator definition in Page design view.

AdCreated event can be trapped

Page 59: Ch3 server controls

TAGS IN ADROTATOR’S XML FILE

TAG Description

<ImageUrl> The image that will be displayed.

<NavigateUrl> The link will be followed if user clicks the banner.

<Alternate> The text will be displayed in place of picture.

<Impression>A new ad is selected whenever the Web page refreshes. An impression attribute can be assigned to each ad. It controls how often an ad is selected relative to other ad in ad file

Page 60: Ch3 server controls

CALENDAR CONTROL <asp:Calendar ID="Calendar2"

runat="server"></asp:Calendar>


Recommended