Sie sind auf Seite 1von 61

Lp trnh Web

Chng: 06

Web Controls

Lp trnh Web

Ni dung
Stepping Up to Web Controls

Web Control Classes


List Controls Table Controls Web Control Events and AutoPostBack A Simple Web Page

Lp trnh Web

Stepping Up to Web Controls


Basic Web Control Classes

The Web Control Tags

Lp trnh Web

Stepping Up to Web Controls


Every HTML control corresponds directly to an HTML

tag. Meaning youre bound by the limitations and abilities of HTML.


Web controls have no such restriction

Lp trnh Web

Advantages of Web control


Provide a rich user interface: A web control is programmed as an object but doesnt necessarily correspond to a single element in the final HTML page. Provide consistent object model: Depending on the properties you set, the underlying HTML element that ASP.NET renders may differ. Tailor their output automatically: ASP.NET server controls can detect the type of browser and automatically adjust the HTML code they write to take advantage of features Provide high-levers: web controls allow you to access additional events, properties, and methods that dont correspond directly to typical HTML controls. Lp trnh Web

Basic Web Control Classes


The ASP.NET Web controls and the .NET Windows controls have

many striking similarities.


Some controls (such as Button and TextBox) can be rendered as

different HTML elements. In this case, ASP.NET uses the element that matches the properties youve set.
Some controls have no real HTML equivalent. (the CheckBoxList

and RadioButtonList controls output as a <table> that contains multiple HTML check boxes or radio buttons.
Table in next slide lists the basic control classes and the HTML

elements they generate

Lp trnh Web

Basic Web Controls


Control Class Underlying HTML Element

Label Button
TextBox CheckBox RadioButton Hyperlink

LinkButton ImageButton Image

<span> <input type="submit"> or <input type="button"> <input type="text">, <input type="password">, or <textarea> <input type="checkbox"> <input type="radio"> <a> <a> with a contained <img> tag <input type="image"> <img>

Lp trnh Web

Basic Web Controls


Control Class ListBox DropDownList CheckBoxList RadioButtonList BulletedList Panel Table, TableRow, and TableCell Underlying HTML Element <select size="X"> where X is the number of rows that are visible at once <select> A list or <table> with multiple <input type="checkbox"> tags A list or <table> with multiple <input type="radio"> tags An <ol> ordered list (numbered) or <ul> unordered list (bulleted) <div> <table>, <tr>, and <td> or <th>
Lp trnh Web

The Web Control Tags


ASP.NET tags have a special format. They always begin with the prefix asp: followed by the

class name.
If there is no closing tag, the tag must end with />. Each attribute in the tag corresponds to a control property,

except for the runat="server" attribute, which signals that the control should be processed on the server.
Lp trnh Web

The Web Control Tags


An ASP.NET TextBox tag:

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


A customized TextBox:

<asp:TextBox ID="txt" BackColor="Yellow Rows="5 ReadOnly="True" TextMode=MultiLine" Text="Hello World runat="server" />

Lp trnh Web

10

The Web Control Tags


Result of the customized TextBox in web browser:

<textarea name="txt" rows="5" cols="20" readonly="readonly" ID="txt style="background-color:Yellow;> Hello World </textarea>
Lp trnh Web

11

Notes
Tag names, property names, and enumeration values in

web control tags are case-sensitivity.

<asp:Button ID="Button1" runat="server Enabled="False" Text="Button" Font-Size="XXSmall" /> <asp:button ID="Button2" runat="server" Enabled="false" tExT="Button />
However, the tags that apply settings in the web.config

file or the machine.config file case must match exactly


Lp trnh Web

12

Web Control Classes


The WebControl Base Class

Units
Enumerations Colors Fonts Focus The Default Button

13

Lp trnh Web

The web control hierarchy

Lp trnh Web

14

The WebControl Base Class


Most web controls begin by inheriting from the

WebControl base class


This class defines the essential functionality for tasks

such as data binding and includes some basic properties that you can use with almost any web control

Lp trnh Web

15

WebControl Properties
Property Description

AccessKey

BackColor, ForeColor and BorderColor BorderWidth BorderStyle Controls

Specifies the keyboard shortcut as one letter. (Supported only on Internet Explorer 4.0 and higher) Sets the colors used for the background, foreground, and border of the control.
Specifies the size of the control border One of the values from the BorderStyle enumeration. Provides a collection of all the controls contained inside the current control.
Lp trnh Web

16

WebControl Properties
Property Description

Enabled EnableViewState

Set this to false to disable the automatic state management for this control. Font Specifies the font used to render any text in the control as a System.Web.UI.WebControls.FontInfo object Height and Width Specifies the width and height of the control

Page
Parent

Provides a reference to the web page that contains this control as a System.Web.UI.Page object. Provides a reference to the control that contains this control
Lp trnh Web

17

WebControl Properties
Property TabIndex ToolTip Visible Description A number that allows you to control the tab order Displays a text message when the user hovers the mouse above the control When set to false, the control will be hidden and will not be rendered to the final HTML page that is sent to the client

Lp trnh Web

18

Units
All the properties that use measurements require the Unit

structure, which combines a numeric value with a type of measurement (pixels, percentage, and so on).
This means when you set these properties in a control tag,

you must make sure to append px (pixel) or % (for percentage) to the number to indicate the type of unit

Lp trnh Web

19

Example:
A Panel control that is 300 pixels wide and has a height

equal to 50 percent of the current browser window:


<asp:Panel Height="300px" Width="50%" ID="pnl runat="server" />

Lp trnh Web

20

Units
You can assigning a unit-based property through code by

use one of the static methods of the Unit type:


Unit.Pixel() to supply a value in pixels,

// Convert the number 300 to a Unit object // representing pixels, and assign it. pnl.Height = Unit.Pixel(300);
Unit.Percentage() to supply a percentage value.

// Convert the number 50 to a Unit object // representing percent, and assign it. pnl.Width = Unit.Percentage(50);
Lp trnh Web

21

Units
You could also manually create a Unit object and

initialize it using one of the supplied constructors and the UnitType enumeration
// Create a Unit object. Unit myUnit = new Unit(300, UnitType.Pixel); // Assign the Unit object to several controls or properties. pnl.Height = myUnit; pnl.Width = myUnit;

Lp trnh Web

22

Enumerations
Enumerations are used heavily in the .NET class library

to group a set of related constants. In code, you set an enumeration using the dot syntax:
ctrl.BorderStyle = BorderStyle.Dashed;
In the .aspx file, you set an enumeration by specifying

one of the allowed values as a string:


<asp:Label BorderStyle="Dashed" Text="Border Test" ID="lbl runat="server" />
Lp trnh Web

23

Colors
The Color property refers to a Color object from the

System.Drawing namespace. You can create color objects in several ways:


Using an ARGB (alpha, red, green, blue) color value:

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

// Create a color using a .NET name ctrl.ForeColor = Color.Crimson;


Lp trnh Web

24

Colors
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");
When defining a color in the .aspx file, you can use any

one of the known color names


<asp:TextBox ForeColor="Red" Text="Test" ID="txt" runat="server" />
Or you can use a hexadecimal color number (in the

format #<red><green><blue>)
<asp:TextBox ForeColor="#ff50ff" Text="Test ID="txt" runat="server" /> Lp trnh Web
25

Fonts
The Font property actually references a full FontInfo

object. FontInfo Properties:


Property Name Names Size Description A string indicating the font name (such as Verdana). An array of strings with font names, in the order of preference. The size of the font as a FontUnit object

Bold, Italic, Strikeout, Boolean properties that apply the given Underline, and Overline style attribute
Lp trnh Web

26

Fonts
In code, you can assign a font using the familiar dot

syntax:
ctrl.Font.Name = "Verdana"; ctrl.Font.Bold = true; // Specifies a relative size. ctrl.Font.Size = FontUnit.Small; // Specifies an absolute size of 14 pixels. ctrl.Font.Size = FontUnit.Point(14);

Lp trnh Web

27

Fonts
In the .aspx file, you need to use a special object walker

syntax to specify object properties such as Font. The object walker syntax uses a hyphen (-) to separate properties
<asp:TextBox Font-Name="Tahoma" Font-Size="40" Text="Size Test" ID="txt runat="server" />

<asp:TextBox Font-Name="Tahoma" Font-Size="Large" Text="Size Test ID="txt" runat="server" />

Lp trnh Web

28

Notes
If the client computer doesnt have the font you request, it

reverts to a standard font.


To deal with this problem, its common to specify a list of

fonts, in order of preference.


To do so, you use the Font.Names property instead of

Font.Name
<asp:TextBox Font-Names="Verdana,Tahoma,Arial" Text="Size Test" ID="txt" runat="server" />
Lp trnh Web

29

Focus
Unlike HTML server controls, every web control

provides a Focus() method.


The Focus() method affects only input controls. When your code is finished processing and the page is

rendered, ASP.NET adds an extra block of JavaScript code to the end of your page. If you havent called Focus() at all, this code isnt added to the page

Lp trnh Web

30

Focus
You can set a control that should always be focused by

setting the DefaultFocus property of the <form> tag


<form DefaultFocus="TextBox2" runat="server">
Another way to manage focus is using access keys. For example, if you set the AccessKey property of a

TextBox to A, pressing Alt+A focus will switch to the TextBox

Lp trnh Web

31

The Default Button


The default button is the button that is clicked when the

user presses the Enter key. To designate a default button, you must set the HtmlForm.DefaultButton property with the ID of the respective control
<form DefaultButton="cmdSubmit" runat="server">

Lp trnh Web

32

The Default Button


The default button must be a control that implements the

IButtonControl interface.
The interface is implemented by the Button, LinkButton,

and ImageButton web controls but not by any of the HTML server controls.
In some cases, it makes sense to have more than one

default button.

Lp trnh Web

33

The Default Button


In some cases, it makes sense to have more than one

default button.
For example, you might create a web page with two groups

of input controls. Both groups may need a different default button.


You can handle this by placing the groups into separate

panels.
The Panel control also exposes the DefaultButton

property, which works when any input control it contains gets the focus.
Lp trnh Web

34

List Controls
Multiple-Select List Controls

The BulletedList Control

35

Lp trnh Web

List Controls
The list controls include the ListBox, DropDownList,

CheckBoxList, RadioButtonList, and BulletedList.


They all work in essentially the same way but are

rendered differently in the browser.


The BulletedList is the the only list control that isnt

selectable.

Lp trnh Web

36

List Controls
All the selectable list controls provide a SelectedIndex

property that indicates the selected row as a zero-based index Selectable list controls also provide an additional SelectedItem property, which allows your code to retrieve the ListItem object that represents the selected item.
The ListItem object provides three important properties:
Text: the displayed content,
Value: the hidden value from the HTML markup, and Selected: true or false depending on whether the item is

selected.

Lp trnh Web

37

Multiple-Select List Controls


Some list controls can allow multiple selections. This isnt allowed for the DropDownList or

RadioButtonList
But it is supported for a ListBox. You have set the

SelectionMode property to the enumerated value ListSelectionMode.Multiple.


With the CheckBoxList, multiple selections are always

possible.
Lp trnh Web

38

Multiple-Select List Controls


You can find all the selected items by iterating through

the Items collection of the list control and checking the ListItem.Selected property of each item.

Lp trnh Web

39

Example:
Reference:
Beginning ASP.NET 3.5 in C sharp 2008 From Novice to

Professional, 2nd edittion, Apress ( page 183 185)

Lp trnh Web

40

The BulletedList Control


Reference:
Beginning ASP.NET 3.5 in C sharp 2008 From Novice to

Professional, 2nd edittion, Apress ( page 185 186)

Lp trnh Web

41

Table Controls

42

Lp trnh Web

Table Controls
Reference:
Beginning ASP.NET 3.5 in C sharp 2008 From Novice to

Professional, 2nd edittion, Apress ( page 186 191)

Lp trnh Web

43

Web Control Events and AutoPostBack


How Postback Events Work

The Page Life Cycle

44

Lp trnh Web

The page processing sequence

Lp trnh Web

45

Web Control Events and AutoPostBack


Some events, such as the Click event of a button, do

occur immediately. Thats because when clicked, the button posts back the page.
However, other actions do cause events but dont trigger

a postback.
You might want to respond to these events, but without a

postback your code has no way to run.


Lp trnh Web

46

How can you write server code that will react immediately to an event that occurs on the client ???

Lp trnh Web

47

Web Control Events and AutoPostBack


ASP.NET handles this by giving you two options:
You can wait until the next postback to react to the event. You can use the automatic postback feature to force a

control to post back the page immediately when it detects a specific user action
All input web controls support automatic postbacks

Lp trnh Web

48

Web Control Events


Event Web Controls That Provide It Always Posts Back Button, ImageButton True

Click

TextChanged

TextBox (fires only after the user changes the focus to another control)
CheckBox, RadioButton

False

CheckedChanged SelectedIndexChanged

False

DropDownList, ListBox, False CheckBoxList, RadioButtonList


Lp trnh Web

49

Web Control Events and AutoPostBack


If you want to capture a change event (such as TextChanged,

CheckedChanged, or SelectedIndexChanged) immediately, you need to set the controls AutoPostBack property to true.
When the page is posted back, ASP.NET will examine the

page, load all the current information, and then allow your code to perform some extra processing before returning the page back to the user.
Depending on the result you want, you could have a page that

has some controls that post back automatically and others that dont
Lp trnh Web

50

Notes
Automatic postbacks can sometimes make the page less

responsive.
Youll learn how to create pages that update themselves

without a noticeable page refresh when you consider ASP.NET AJAX in Chapter 25

Lp trnh Web

51

The postback processing sequence


Page object is created from .aspx file Page.Init event occurs Controls are repopulated with information from view state Page.Load event occurs All other events occurs (like Click and Change events) Page.PreRender event occurs Control information is stored in view state

HTML for page is rendered (and can nolonger be change)


Page.Unload event occurs Page object is released from memory
Lp trnh Web

52

How Postback Events Work


If you create a web page that includes one or more web

controls that are configured to use AutoPostBack,


ASP.NET adds a special JavaScript function to the rendered

HTML page ( __doPostBack() function )


ASP.NET also adds two additional hidden input fields

(__EVENTTARGET and __EVENTARGUMENT)


Finally, any control that has its AutoPostBack property set to

true is connected to the __doPostBack() function using the onclick or onchange attributes.
Lp trnh Web

53

How Postback Events Work


The __doPostBack() function.
When called, it triggers a postback, sending data back to the

web server. The __doPostBack() function has the responsibility for setting these values with the appropriate information about the event and then submitting the form.
<script language="text/javascript"> function __doPostBack(eventTarget, eventArgument) { var theform = document.Form1; theform.__EVENTTARGET.value = eventTarget; theform.__EVENTARGUMENT.value = eventArgument; theform.submit(); } </script>

Lp trnh Web

54

How Postback Events Work


Two additional hidden input fields: __EVENTTARGET and
__EVENTARGUMENT

are used to pass information back to the server. This information consists of the ID of the control that raised

the event and any additional information that might be relevant. <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" /> <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
Lp trnh Web

55

An automatic postback

Lp trnh Web

56

The Page Life Cycle


What happens when a user changes a control that has the

AutoPostBack property set to true?

Lp trnh Web

57

Client side

1. The JavaScript __doPostBack function is invoked, and the page is resubmitted to the server
2. ASP.NET re-creates the Page object using the .aspx file. 3. ASP.NET retrieves state information from the hidden view state field and updates the controls accordingly 4. The Page.Load event is fired.

Server side

5. The appropriate change event is fired for the control. (If more than one control has been changed, the order of change events is undetermined.)
6. The Page.Unload event fires, and the page is rendered (transformed from a set of objects to an HTML page). 7. The new page is sent to the client.
Lp trnh Web

58

Example:
Reference:
Beginning ASP.NET 3.5 in C sharp 2008 From Novice to

Professional, 2nd edittion, Apress ( page 197 199)

Lp trnh Web

59

A Simple Web Page (Lab)


Improving the Greeting Card Generator

Generating the Cards Automatically

60

Lp trnh Web

A Simple Web Page (Lab)


Reference:
Beginning ASP.NET 3.5 in C sharp 2008 From Novice to

Professional, 2nd edittion, Apress ( page 199 208)

Lp trnh Web

61

Das könnte Ihnen auch gefallen