+ All Categories
Home > Documents > 4. ASP.NET Server Controls - WBC Software Lab: …. ASP.NET Server Controls A control is a reusable...

4. ASP.NET Server Controls - WBC Software Lab: …. ASP.NET Server Controls A control is a reusable...

Date post: 25-May-2018
Category:
Upload: phamdiep
View: 227 times
Download: 0 times
Share this document with a friend
29
38 4. ASP.NET Server Controls A control is a reusable piece of software functionality that usually provides a visible interface. Server controls are those controls that run on a server (vs. Windows Forms controls). In addition to using <% %> to code blocks to program dynamic content, Web Forms pages developer can use ASP.NET server controls to generate HTML elements. Server controls are declared within an .aspx file using custom tags or intrinsic HTML tags that contain a runat=””server” attribute value. Some examples of server controls declarations are: <input type=”text” id=”Name” runat=”server” /> .... <asp:textbox runat=”server” /> ...... <asp:button runat=”server” /> ....... The server controls provided in .NET fall quite neatly into six groups: HTML server controls ASP.NET validation controls ASP.NET Web Forms controls ASP.NET List controls ASP.NET Rich controls ASP.NET mobile controls The .NET Framework class library contains several classes that represent server controls. These classes are divided into two categories: HTML controls and Web Forms (asp) controls.
Transcript

38

4. ASP.NET Server Controls A control is a reusable piece of software functionality that usually provides a visible interface. Server controls are those controls that run on a server (vs. Windows Forms controls). In addition to using <% %> to code blocks to program dynamic content, Web Forms pages developer can use ASP.NET server controls to generate HTML elements. Server controls are declared within an .aspx file using custom tags or intrinsic HTML tags that contain a runat=””server” attribute value. Some examples of server controls declarations are: <input type=”text” id=”Name” runat=”server” /> .... <asp:textbox runat=”server” /> ...... <asp:button runat=”server” /> ....... The server controls provided in .NET fall quite neatly into six groups: • HTML server controls • ASP.NET validation controls • ASP.NET Web Forms controls • ASP.NET List controls • ASP.NET Rich controls • ASP.NET mobile controls

The .NET Framework class library contains several classes that represent server controls. These classes are divided into two categories: HTML controls and Web Forms (asp) controls.

39

HTML Controls Intrinsic HTML tags are handled by one of the control class in the

System.Web.UI.HtmlControls namespace, such as HtmlGenericControl, HtmlForm, HtmlButton, and so on. There are around 100 elements currently defined in HTML. Rather than provide a distinct class for each of the HTML elements, the .NET framework contains specific classes for only a few of them. These mainly include those elements that used on the HTML <form>. If there is no specific class for an element, the framework substitutes the HtmlGenericControl class for the element. The HTML control class hierarchy is shown below:

HTML control classes are instantiated by adding runat=”server” to ordinary HTML tags. For example, the following line declares a standard HTML text input field: <input type=”text” id =”name”> But this line declares an instance of the HtmlInputText class: <input type=”text” id=”name” runat=”server” />

40

HTML Controls and the Corresponding Tags

Control Type HTML Tag

HtmlAnchor <a>

HtmlButton <button>

HtmlSelect <select>

HtmlTextArea <textarea>

HtmlInputButton <input type="button">

HtmlInputCheckBox <input type="check">

HtmlInputRadioButton <input type="radio">

HtmlInputText <input type="text"> and <input type="password">

HtmlInputHidden <input type="hidden">

HtmlInputImage <input type="image">

HtmlInputFile <input type="file">

HtmlForm <form>

HtmlImage <img>

HtmlTable <table>

HtmlTableRow <tr>

HtmlTableCell <td>

HtmlGenericControl Any other unmapped tag, such as <span> and <div>

The HTML controls are provided primarily to ease the chore of migrating existing ASP applications to ASP.NET. For example, rather than replacing all instances of <input type=”text”> with <asp:textbox /> you can simply add runat=”server” to the existing tags to convert them into Web Forms controls.

41

Web Forms Controls Most Web control classes derive either directly or indirectly from the WebControl class, which is a member of the .NET namespace, System.Web.UI.WebControls.

Compared with HTML controls, Web controls are much rich in UI and more ambitious in functionality. For example, you can use a Calendar control to display calendars in Web Forms and let users pick dates using a GUI. The attributes that you can apply to tags when declaring Web controls are determined by the properties defined in the respective control classes. For example, since the TextBox class exposes properties named TextMode and Text, all of the following statements are valid:

<asp:TextBox Text="Hello" RunAt="server" /> <asp:TextBox Text="Hello" TextMode="singleline" RunAt="server" /> <asp:TextBox Text="Hello" TextMode="multiline" RunAt="server" /> <asp:TextBox Text="Hello" TextMode="password" RunAt="server" />

42

A partial list of common set of properties inherited from the WebControl class is given below: Properties Inherited from WebControl

Property Description

BackColor Gets or sets the control's background color

BorderColor Gets or sets the control's border color

BorderStyle Gets or sets the control's border style

BorderWidth Gets or sets the control's border width

Font Gets or sets the control font

ForeColor Gets or sets the control's foreground color

Height Gets or sets the height of the control

ID Gets or sets the control ID

TabIndex Gets or sets the control's tab index

ToolTip Gets or sets the tooltip to display for the control

Visible Gets or sets the control's visibility state

Width Gets or sets the width of the control

Syntax is important when using these properties, particularly the Font, Width, Height, and xxxColor properties. The Font property has sub-properties named Bold, Italic, Name, Names, Size, Strikeout, Underline, and Overline. To assign a value to a sub-property, separate the property name (e.g. Font) and the sub-property name with a hyphen, as in

<asp:Button Text="OK" RunAt="server" Font-Name="Verdana" Font-Bold="True" /> The Font-Size property can be specified using pixels as the unit of measurement using either of the following syntactical conventions:

<asp:Button Text="OK" Font-Size="10" RunAt="server" /> <asp:Button Text="OK" Font-Size="10px" RunAt="server" />

Or it can be expressed in points by replacing px with pt:

<asp:Button Text="OK" Font-Size="10pt" RunAt="server" />

43

Width, Height, and BorderWidth values can be expressed in pixels, points, or percentages. Pixels is the default, so omitting px, pt, and % is the equivalent of writing out px.

<asp:Button Text="OK" Width="100" RunAt="server" /> <asp:Button Text="OK" Width="100px" RunAt="server" /> <asp:Button Text="OK" Width="100pt" RunAt="server" /> <asp:Button Text="OK" Width="100%" RunAt="server" />

Color properties can be initialized using standard HTML color names (honeydew, mistyrose, oldlace, and so on) or hexadecimal RGB color values (such as #ffffff for white):

<asp:Button Text="OK" RunAt="server" BackColor="lightseagreen" ForeColor="#ffffff" />

Most Web controls implement additional control-specific properties above and beyond those listed in the above Figure. For example, many of the code listings in this section use a property named Text to assign text to Buttons and TextBoxes. Text is not inherited from WebControl, but instead is declared in TextBox and Button. Consult the .NET documentation for a complete list of all the properties exposed by individual control class.

44

4.1 ASP.NET Server Control Event Model Server control processing is based on an event-driven model. However, events raised by ASP.NET server controls work somewhat differently than events in traditional client forms or in client-based Web applications. The difference arises primarily because of the separation of the event itself from where the event is handled.

In client-based applications, events are raised and handled on the client. In Web Forms pages, on the other hand, events associated with server controls are raised on the client but handled on the Web server by the ASP.NET page framework. For events raised on the client, the Web Forms control event model requires that the event information be captured on the client and an event message transmitted to the server, via an HTTP post message. The page framework must interpret the post to determine what event occurred and then call the appropriate method in your code on the server to handle the event. This event model is illustrated in the following picture.

ASP.NET handles virtually all the mechanics of capturing, transmitting, and interpreting the event. When you create event handlers in a Web Forms page, you can do so without thinking about the mechanics of how the event information is captured and made available to your code. Instead, you can create event handlers in much the same way you would do so in a traditional client form.

45

Example This example shows a Web Forms page (first.aspx ), the HTML pages it generates (when it is first requested) and re-generates (when it is post-backed). Web Forms page (first.aspx) requested <html> <script language="C#" runat="server"> void EnterBtn_Click(Object Src, EventArgs E) { Message.Text = "Hi " + Name.Text + ", welcome to ASP.NET!"; } </script> <body> <form runat="server"> Enter your name: <asp:textbox id="Name" runat=server/> <asp:button text="Enter" Onclick="EnterBtn_Click" runat="server"/> <p> <asp:label id="Message" runat=server/> </form> </body> </html>

When the above Web Forms page is first requested, the following HTML page is generated and sent to the browser. <html> <body> <form name="_ctl0" method="post" action="first.aspx" id="_ctl0"> <input type="hidden" name="__VIEWSTATE" value="dDwxMzc4MDMwNTk1Ozs+3Y2pAiEcSEBAOi1H6qsG4tQkhuQ=" /> Enter your name: <input name="Name" type="text" id="Name" /> <input type="submit" name="_ctl1" value="Enter" /> <p> <span id="Message"></span> </form> </body> </html>

46

For example, while the user interacts with the above HTML page, the user enters “John” to the text box and clicks the Enter button. As a result, the browser sends an HTTP post message (with <form> input data) to the server’s first.aspx. On the server, first.aspx reconstructs an HTML page, which is then returned to the client browser. The returned HTML page is shown below: <html> <body> <form name="_ctl0" method="post" action="first.aspx" id="_ctl0"> <input type="hidden" name="__VIEWSTATE" value="dDwxMzc4MDMwNTk1O3Q8O2w8aTwyPjs+O2w8dDw7bDxpPDU+Oz47bDx0PHA8cDxsPFRleHQ7PjtsPEhpICwgd2VsY29tZSB0byBBU1AuTkVUITs+Pjs+Ozs+Oz4+Oz4+Oz7rzPKy5igbFjeSSanvhwvd+HI5eQ==" /> Enter your name: <input name="Name" type="text" id="Name" /> <input type="submit" name="_ctl1" value="Enter" /> <p> <span id="Message">Hi John, welcome to ASP.NET!</span> </form> </body> </html>

The following paragraphs describe some aspects of event handling in Web Forms pages that are important to Web Forms page programming. Intrinsic Event Set

Because most Web Forms events require a round trip to the server for processing, they can affect the performance of a form. Therefore, server controls offer a limited set of intrinsic events, usually only click-type events. Some server controls support a special version of the onchange event, which is raised when the control's value changes. For example, the CheckBox server control raises a change event when the user clicks the box. Events that occur often (and can be raised without the user knowing it), such as an onmouseover event, are not supported for server controls.

Note that some server controls support a set of higher-level events. For example, the Calendar Web server control raises a SelectionChanged event that is a more abstract version of a Click event. Event Arguments

Web and HTML server control events follow a standard .NET Framework pattern for event handler methods. All events pass two arguments: an object representing the object that raised the event, and an event object containing any event-specific

47

information. The second argument is usually of type System.EventArgs, but for some controls is of a type specific to that control. For example, for an ImageButton Web server control, the second argument is of the type ImageClickEventArgs, which includes information about the coordinates where the user has clicked. Postback and non-Postback Events in Server Controls

In Web server controls, certain events, typically click events, cause the form to be posted back to the server. Change events in HTML server controls and Web server controls, such as the TextBox control, are captured but do not immediately cause a post. Instead, they are cached by the control until the next time a post occurs. Then, when the page is processed on the server again, all the pending events are raised and processed. If the browser supports it, validation controls can check user input using client script, without a round trip to the server.

During server page processing, events are processed first, in no particular order. When all change events have been processed, the click event that caused the form to be posted is processed. As such, you should not create application logic that relies on the change events being raised in a specific order unless you have detailed knowledge of page event processing. Example Consder the first.aspx page shown again in the following: <html> <script language="C#" runat="server"> void EnterBtn_Click(Object Src, EventArgs E) { Message.Text = "Hi " + Name.Text + ", welcome to ASP.NET!"; } </script> <body> <form runat="server"> Enter your name: <asp:textbox id="Name" runat=server/> <asp:Button text="Enter" Onclick="EnterBtn_Click" runat="server"/> <p> <asp:Label id="Message" runat=server/> </form> </body> </html>

This click event will automatically post back to the server, which meanswhen the user clicks this button, the browser will immediately sent an HTTP POST-request message to the server. In fact, this server control (asp:Button) outputs this HTML element <input type="submit" name="_ctl1" value="Enter" /> to the browser.

48

As said before, because a postbactk requires a rather expensive round trip, for most server control events, the AutoPostBack property is set to false by default. As such, most control events will be raised only during the post-back caused by other event such as a button click.

Example This server control <asp:TextBox id="txtPostBack" style="Z-INDEX: 101; LEFT: 204px;

POSITION: absolute; TOP: 221px" runat="server" AutoPostBack="True"></asp:TextBox>

generates this HTML fragment to the client browser: <script language="javascript"> <!-- function __doPostBack(eventTarget, eventArgument) { var theform = document.Form1; theform.__EVENTTARGET.value = eventTarget; theform.__EVENTARGUMENT.value = eventArgument; theform.submit(); } // --> </script> <input name="txtPostBack" type="text" id="txtPostBack" onchange="__doPostBack('txtPostBack','')"

language="javascript" style="Z-INDEX: 101; LEFT: 204px; POSITION: absolute; TOP: 221px" />

49

Example This example creates a custom button, MyButton, that causes postback, captures the postback event, and raises a Click event on the server. using System; using System.Web.UI; namespace CustomControls { public class MyButton: Control, IPostBackEventHandler { // Defines the Click event. public event EventHandler Click; // Invokes delegates registered with the Click event. protected virtual void OnClick(EventArgs e) { if (Click != null) Click(this, e); } // Method of IPostBackEventHandler that raises change events. public void RaisePostBackEvent(string eventArgument) { OnClick(EventArgs.Empty); } protected override void Render(HtmlTextWriter output) { output.Write("<INPUT TYPE = submit name = " + this.UniqueID + " Value = 'Click Me' />"); } } } The following ASP.NET page uses the custom button MyButton, defined above. <%@ Register TagPrefix="Custom" Namespace="CustomControls" Assembly = "CustomControls" %> <script language="C#" runat=server> private void Button_Click(Object sender, EventArgs e) { TextBox.BackColor = System.Drawing.Color.Green; TextBox.Text = "You clicked the button"; } </script> <html> <body> <form runat=server> Here is the custom button.<br> <Custom:MyButton Id = "Button" OnClick = "Button_Click"

runat=server/> <br><br> <asp:TextBox id = "TextBox" Text = "Click the button" Width = "200" BackColor = "Cyan" runat=server/> <br></form> </body> </html>

50

You can specify that a change event cause a form post. Web server controls that support a change event include an AutoPostBack property. When this property is true, the control's change event causes the form to post immediately, without waiting for a click event. For example, by default, a CheckBox control's CheckedChange event does not cause the page to be submitted. However, by setting the control's AutoPostBack property to true, you specify that as soon as a user clicks the check box, the page is sent to the server for processing. For the AutoPostBack property to work properly, the user's browser must be set to allow scripting. This is the default in most cases. However, some users disable scripting for security reasons. Application and Session Events

In addition to page and control events, the ASP.NET page framework provides ways for you to work with events that can be raised when your application starts or stops or when an individual user's session starts or stops.

Application events are raised for all requests to an application. For example,

Application_BeginRequest is raised when any Web Forms page or XML Web service in your application is requested. This event allows you to initialize resources that will be used for each request to the application. A corresponding event, Application_EndRequest, provides you with an opportunity to close or otherwise dispose of resources used for the request.

Session events are similar to application events (there is a Session_OnStart and

a Session_OnEnd event), but are raised with each unique session within the application. A session begins when a user requests a page for the first time from your application and ends either when your application explicitly closes the session or when the session times out. You can create delegates for these types of events in the Global.asax file. Bubbled Events

Web server controls such as the Repeater, DataList, and DataGrid controls can contain button controls that themselves raise events. For example, each row in a DataGrid control can contain one or more buttons created dynamically by templates. Rather than each button raising an event individually, events from the nested controls are bubbled — that is, they're sent to the container. The container in turn raises a generic event called ItemCommand with parameters that allow you to discover which individual control raised the original event. By responding to this single event, you can avoid having to write individual event handlers for child controls.

The ItemCommand event includes the two standard event arguments, an object referencing the source of the event and an event object containing event-specific information. The DataGrid and DataList Web server controls support additional events, such as EditCommand, DeleteCommand, and UpdateCommand, which are special cases of bubbled events.

51

With buttons, you can use the CommandArgument property to pass a user-specified string to the event handler to help you identify what button raised the event. For example, in a DataList control, buttons raise the ItemCommand event. You can set the CommandArgument property of each button to a different value — perhaps one button's value is "ShowDetails" and another button's value is "AddToShoppingCart" and then capture those values in the event handler later. Event Delegates in Web Forms Pages

An event is a message — effectively, something like "a button has been clicked". In your application, you want the message to be translated into a method call in your code, such as "Button1_Click". The binding between the event message and a specific method — that is, an event handler — is done using an event delegate.

In Web Forms pages, you typically do not need to explicitly code delegates. If

you use the Web Forms Designer in Visual Studio, the designer generates code that automatically binds events to methods. In C#, the designer generates an explicit event-handler delegate in the page, similar to the following:

private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load);}

Alternatively, the ASP.NET page framework also supports an automatic way to associate page events and methods. If the AutoEventWireup attribute of the Page directive is set to true (or if it is missing, since by default it is true), the page framework calls page events automatically, specifically the Page_Init and Page_Load methods. In that case, no explicit delegate is needed. The disadvantage of the AutoEventWireup attribute is that it requires that the page event handlers have specific, predictable names. This limits your flexibility in how you name your event handlers. Therefore, in Visual Studio, when you create a new Web Forms project, the AutoEventWireup attribute is set to false by default and the designer generates explicit code to bind page events to methods.

If you do set AutoEventWireup to true, Visual Studio will generate code to bind the events and the page framework will automatically call events based on their names. This can result in the same event code being called twice when the page runs. As a consequence, you should always leave AutoEventWireup set to false when working in Visual Studio. Responding to Both Client and Server Events in ASP.NET Server Controls

For the most part, you will be primarily interested in events that are raised in server code. However, if it is appropriate for your application, you can also handle client-side events for ASP.NET server controls by writing client script. You cannot use HTML syntax to bind to client-side events for Web server controls. Instead, you have to add event-binding attributes in code. For example, you might have an HTML image button

52

element that you have converted to an HTML server control. Typically, in a Web Forms page you would handle the image button's click event in server code. However, you might also want to use client code to change the image when the user moves the mouse over it. You can do that by creating a client script for the image button's onmouseover event. (In this example, the assumption is that you are working with a browser that supports HTML 4.0, such as Microsoft Internet Explorer 4.0 or later.)

In the case that both the client-side event handler and a server-side event handler have the same event-handler name, the client-side event handler always runs first, then the server event handler. However, it is confusing to allow this scenario, so some planning for a naming convention is strongly suggested.

Handling a Click Event in Client and Server Code

There is one event — the client onclick event — that introduces a difficulty if you want to handle it on both the client and the server. The problem arises because all button server controls (and other controls whose AutoPostBack property is set to true) submit the page to the server. However, in HTML, only a few controls inherently submit a form: The HTML submit button (<input type=submit>), which is the HtmlInputButton control with its type set to Submit or Image. You can add this control from the HTML tab of the Toolbox. The Button Web server control (<asp:button>), in fact, generates the HTML element: <input type=”submit” ....... />. For all other controls that are specified to submit the page, a small client script is written into the page and called to submit the form when the control is clicked. Those controls therefore already use the client-side OnClick event to invoke this submit script. You can create client-side OnClick handlers for all controls, but you need to choose the approach that works with each type of control.

53

4.2 Server Control Programming Using Visual Studio Designer, you can visually design GUI in either Windows Forms or Web Forms applications. In both types of Forms applications, although there are some differences in available controls (based on System.Windows.Forms.Control in Windows Forms and System.Web.UI.Control in Web Forms) the concepts and techniques behind the Designer are the same. You use the Designer to:

• Visually layout controls in the form. • Select and manipulate a control (e.g. change control properties and install control

event handlers). Classification of Server Controls By control’s functions, it is convenient to classify server controls into the following groups:

1. HTML controls 2. Basic Web Forms controls (sort of refined HTML controls) 3. List-bound controls (supporting data source and data binding) 4. Validation controls 5. Rich controls (such as Calendar and Ad Rotator) 6. Mobile controls (light-weight Web Forms controls for small-screens used with

mobile devices) 7. Custom controls (programmer-defined controls)

54

Web Forms Classes in the System.Web.UI.WebControls Namespace Class Description AdCreatedEventArgs Provides data for the AdCreated event of the AdRotator

control. This class cannot be inherited. AdRotator Displays an advertisement banner on a Web page. BaseCompareValidator Serves as the abstract base class for validation controls that

perform typed comparisons. BaseDataList Serves as the abstract base class for data listing controls,

such as the DataList and DataGrid. This class provides the methods and properties common to all data listing controls.

BaseValidator Serves as the abstract base class for validation controls. BoundColumn A column type for the DataGrid control that is bound to a

field in a data source. Button Displays a push button control on the Web page. ButtonColumn A column type for the DataGrid control that contains a

user-defined command button, such as Add or Remove, that corresponds with each row in the column.

Calendar Displays a single month calendar that allows the user to select dates and move to the next or previous month.

CalendarDay Represents a date in the Calendar control. CheckBox Displays a check box that allows the user to select a true or

false condition. CheckBoxList Creates a multi selection check box group that can be

dynamically created by binding the control to a data source.CommandEventArgs Provides data for the Command event. CompareValidator Compares the value entered by the user into an input control

with the value entered into another input control or a constant value.

CustomValidator Performs user-defined validation on an input control. DataGrid A data bound list control that displays the items from data

source in a table. The DataGrid control allows you to select, sort, and edit these items.

DataGridColumn Serves as the base class for the different column types of the DataGrid control.

DataGridColumnCollection A collection of DataGridColumn derived column objects that represent the columns in a DataGrid control. This class cannot be inherited.

DataGridCommandEventArgs Provides data for the CancelCommand, DeleteCommand, EditCommand, ItemCommand, and UpdateCommand events of the DataGrid control. This class cannot be inherited.

DataGridItem Represents an item (row) in the DataGrid control.

55

DataGridItemCollection Represents a collection of DataGridItem objects in a DataGrid control.

DataGridItemEventArgs Provides data for the ItemCreated and ItemDataBound events of the DataGrid control. This class cannot be inherited.

DataGridPageChangedEventArgs Provides data for the PageIndexChanged event of the DataGrid control. This class cannot be inherited.

DataGridPagerStyle Specifies the style for the pager of the DataGrid control. This class cannot be inherited.

DataGridSortCommandEventArgs Provides data for the SortCommand event of the DataGrid control. This class cannot be inherited.

DataKeyCollection Represents a collection that contains the key field of each record in a data source. This class cannot be inherited.

DataList A data bound list control that displays items using templates.

DataListCommandEventArgs Provides data for the CancelCommand, DeleteCommand, EditCommand, ItemCommand, and UpdateCommand events of the DataList control. This class cannot be inherited.

DataListItem Represents an item in the DataList control. DataListItemCollection Represents the collection of DataListItem objects in the

DataList control. This class cannot be inherited. DataListItemEventArgs Provides data for the ItemCreated and ItemDataBound

events of a DataList control. This class cannot be inherited.DayRenderEventArgs Provides data for the DayRender event of the Calendar

control. This class cannot be inherited. DropDownList Represents a control that allows the user to select a single

item from a drop-down list. EditCommandColumn A special column type for the DataGrid control that

contains the Edit command buttons for editing data items in each row.

FontInfo Encapsulates the font properties of text. This class cannot be inherited.

FontNamesConverter Converts a string containing a list of font names to an array of strings containing the individual names. It also performs the reverse function.

FontUnitConverter Converts a FontUnit to an object with another data type. It also converts an object with another data type to a FontUnit.

HyperLink A control that displays a link to another Web page. HyperLinkColumn A column type for the DataGrid control that contains a

hyperlink for each item in the column. HyperLinkControlBuilder Interacts with the parser to build a HyperLink control. Image Displays an image on a Web page.

56

ImageButton A control that displays an image and responds to mouse clicks on the image.

Label Represents a label control, which displays text on a Web page.

LabelControlBuilder Interacts with the parser to build a Label control. LinkButton Displays a hyperlink style button control on a Web page. LinkButtonControlBuilder Interacts with the parser to build a LinkButton control. ListBox Represents a list box control that allows single or multiple

item selection. ListControl Serves as the abstract base class that defines the properties,

methods, and events common for all list-type controls. ListItem Represents a data item in a data-bound list control. This

class cannot be inherited. ListItemCollection A collection of ListItem objects in a list control. This class

cannot be inherited. ListItemControlBuilder Interacts with the parser to build a ListItem control. Literal Reserves a location on the Web page to display static text. LiteralControlBuilder Interacts with the parser to build a Literal control. MonthChangedEventArgs Provides data for the VisibleMonthChanged event of a

Calendar. This class cannot be inherited. PagedDataSource Encapsulates the properties of the DataGrid control that

allow it to perform paging. This class cannot be inherited. Panel Represents a control that acts as a container for other

controls. PlaceHolder A container to store dynamically added server controls on

the Web page. PlaceHolderControlBuilder Interacts with the parser to build a PlaceHolder control. RadioButton Represents a radio button control. RadioButtonList Represents a list control that encapsulates a group of radio

button controls. RangeValidator Checks whether the value of an input control is within a

specified range of values. RegularExpressionValidator Validates whether the value of an associated input control

matches the pattern specified by a regular expression. Repeater A data-bound list control that allows custom layout by

repeating a specified template for each item displayed in the list.

RepeaterCommandEventArgs Provides data for the ItemCommand event of a Repeater. This class cannot be inherited.

RepeaterItem Represents an item in the Repeater control. RepeaterItemCollection Represents a collection of RepeaterItem objects in the

Repeater control. This class cannot be inherited.

57

RepeaterItemEventArgs Provides data for the ItemCreated and ItemDataBound events of a Repeater.

RepeatInfo Encapsulates the information used to render a list control that repeats a list of items. This class cannot be inherited.

RequiredFieldValidator Makes the associated input control a required field. SelectedDatesCollection Encapsulates a collection of System.DateTime objects that

represent the selected dates in a Calendar control. This class cannot be inherited.

ServerValidateEventArgs Provides data for the ServerValidate event of the CustomValidator control. This class cannot be inherited.

Style Represents the style of a Web server control. Table Constructs a table and defines its properties. TableCell Represents a cell in a Table control. TableCellCollection Encapsulates a collection of TableHeaderCell and

TableCell objects that make up a row in a Table control. This class cannot be inherited.

TableCellControlBuilder Interacts with the parser to build a TableCell control. TableHeaderCell Represents a heading cell within a Table control. TableItemStyle Represents the style properties for an element of a control

that renders as a TableRow or TableCell. TableRow Represents a row in a Table control. TableRowCollection Encapsulates a collection of TableRow objects that represent

a single row in a Table control. This class cannot be inherited.

TableStyle Represents the style for a table control. This class is primarily used by control developers.

TargetConverter Converts a value representing the location (target) to display the content resulting from a Web navigation to a string. It also converts a string to a target value.

TemplateColumn Represents a column type for the DataGrid control that allows you to customize the layout of controls in the column.

TextBox Constructs a text box and defines its properties. TextBoxControlBuilder Interacts with the parser to build a TextBox control. UnitConverter Converts a Unit to an object of another data type. It also

converts an object of another data type to a Unit. ValidatedControlConverter Converts a control on the Web Forms page that can be

validated with a validation control to a string. ValidationSummary Displays a summary of all validation errors inline on a Web

page, in a message box, or both. WebColorConverter Converts a predefine color name or an RGB color value to

and from a System.Drawing.Color.

58

WebControl Serves as the base class that defines the methods, properties and events common to all controls in the System.Web.UI.WebControls namespace.

Xml Displays an XML document without formatting or using Extensible Stylesheet Language Transformations (XSLT).

ASP.NET Server Controls by Functions Function Control Description Text display (read only) Label Displays text that users cannot directly

edit. Text edit (singe-or multi- lines)

TextBox Displays text that can be edited by users at run time or changed programmatically. Note Although other controls allow users to edit text (for example, DropDownList), their primary purpose is not usually text editing.

Selection from a list DropDownList Allows users to either select from a list or enter text.

ListBox Displays a list of choices. Optionally, the list can allow multiple selections.

Graphics display Image Displays an image. AdRotator Displays a sequence (predefined or

random) of images. Value setting CheckBox Displays a box that users can click to turn

on and off. CheckBoxList Creates a grouping of check boxes. The

list control makes it easy to create check boxes using data binding.

RadioButton Displays a single button that can be turned on or off.

RadioButtonList Creates a grouping of radio buttons. Inside the group, only one button can be selected.

Date setting Calendar Displays a graphic calendar to allow users to select a date.

Commands Note These controls always cause the form to be posted to the server for processing.

Button Performs a task.

LinkButton Like a Button control, but has the appearance of a hyperlink.

59

ImageButton Like a Button control, but incorporates an image instead of text.

Navigation HyperLink Creates a Web navigation link. Table manipulation Table Creates a table. TableCell Creates an individual cell within a table

row. TableRow Creates an individual row within a table. Grouping other controls CheckBoxList Creates a collection of check boxes. Panel Creates a borderless division on the form

that serves as a container for other controls.

RadioButtonList Creates a grouping of radio buttons. Inside the group, only one button can be selected.

Selection from a list Repeater Displays information from a data source using a set of HTML elements and controls you specify, repeating the elements once for each record in the data set.

DataList Like the Repeater control, but with more formatting and layout options, including the ability to display information in a table. The DataList control also allows you to specify editing behavior.

DataGrid Displays information, usually data-bound, in tabular form with columns. Provides mechanisms to allow editing and sorting.

Place holding PlaceHolder Enables you to place an empty container control in the page and then dynamically add child elements to it at run time.

Literal Renders static text into a Web page without adding any HTML elements.

XML Reads XML and writes it into a Web Forms page at the location of the control.

60

Server Control Recommendations You can mix control types on the same page. For example, your Web Forms page might include a form made up of Web server controls plus an HTML server control converted from an HTML <SPAN> element. The following table summarizes when to use Web server controls and when to use HTML server controls. Type of control Use it when Web server control You prefer a Visual Basic-like programming model.

You are writing a Web Forms page that might be used by both HTML 3.2 and HTML 4.0 browsers. You need specific functionality such as a calendar or ad rotator that is available only as a Web server control. You are creating applications with nested controls and want to be able to catch events at the container level.

HTML server control You prefer an HTML-like object model. You are working with existing HTML pages and want to quickly add Web Forms functionality. Because HTML server controls map exactly to HTML elements, they can be supported by any HTML design environment. The control will also interact with client script.

Example The following shows three different ways of implementing a text input in an ASP.NET page: 1. An HTML input element <input type=”text” name=”Address” /> 2. An HTML server control <input type=”text” id=”Address” runat=”server” /> 3. A Web Forms control <asp:TextBox id=”Address” runat=”server” /> What are the differences in these three implementations? What are their advantages and disadvantages?

61

Control Usage Example – The Label Controls (System.Web.UI.WebControls.Label)

Tag name: <asp:Label> Purpose: Display text in Web pages Basic properties: Text

Basic Events: Example <asp:Label Text=”Hello World!” runat=server /> <asp:Label Text=”Hello World!” runat=server > </asp:Label> Example This example assigns the Label control an ID and uses a server-side script to modify the Label’s Text property. <asp:Label ID=”MyLabel” Text=”Hello World!” runat=server /> ............. <% MyLabel.Text = “Goodbye”; %>

62

5. Web User and Customer Controls 5.1 Web User Controls

The ASP.NET server controls provide a great deal of functionality, but they cannot cover every situation. Web user controls enable you to easily define controls as you need them for your applications, using the same programming techniques that you use to write Web Forms pages. You can even convert a Web Forms page into a Web user control with a few modifications. To make sure that a user control cannot be run as a standalone Web Forms page, user controls are identified by the file name extension .ascx. Note that Web user controls are not to be confused with Web custom controls.

A Web user control is similar to a complete Web Forms page, with both a user interface page and a code-behind file. The user interface page differs from an .aspx file in these ways:

1. The extension must be .ascx. 2. The user control does not have <HTML>, <BODY>, and <FORM> elements in it,

simply because user controls are intended to be inserted into a hosting page (as such, these elements must be in the hosting page).

In every other way, a user control is like a Web Forms page. You can use the same HTML elements and Web controls on a user control that you do on a standard Web Forms page. For example, if you are creating a user control to use as a toolbar, you can put a series of Button Web server controls onto the control and create event handlers for the buttons. Creating a Web User Control To create a Web Forms user control using Visual studio .NET, follow these instructions:

1. On the Project menu, click Add Web User Control. Change the name as desired and click Open to open the control in the designer.

2. Add text and controls to the design surface. Any controls that you want to be able to access programmatically must be Web Forms server controls or HTML server controls.

3. Use the Web Forms Designer to set properties and create any code required for your control in the code-behind file.

The following example shows a simple user control that you might use as a menu. The four menu choices are implemented as Hyperlink Web server controls. <%@ Control Language="C#" AutoEventWireup="false" Codebehind="menu.ascx.cs" Inherits="myProj.menu"%> <P> <asp:HyperLink id=lnkLogin runat="server" _ NavigateURL="Login.aspx">Login</asp:HyperLink>&nbsp; | <asp:HyperLink id=lnkAddToCart runat="server" _

63

NavigateURL="Cart.aspx>Add to Cart</asp:HyperLink>&nbsp; | <asp:HyperLink id=lnkTechSupport runat="server" _ NavigateURL="TechSupport.aspx">Technical Support </asp:HyperLink>&nbsp; | <asp:HyperLink id=lnkAbout runat="server" _ NavigateURL="AboutUs.aspx">About Us</asp:HyperLink> Adding Web User Controls to a Web Forms Page

You can add a Web user control to a Web Forms page in Design view by simply dragging the control from Solution Explorer and dropping it where you want it to appear in the page. The Web Forms Designer automatically adds an @ Register directive and a tag for the control to the page. From that point, the control becomes part of the page and is rendered when the page is processed. Also, the control's public properties, events, and methods are exposed to the page and can be worked with programmatically. You can also add user controls to a page programmatically. Note that the user control must be in the same project as the Web Forms page. To add a user control to a Web Forms page in Design view

In the Web Forms Designer, open the Web Forms page you want to add the control to, and make sure that the page is in Design View. Select the user control's file in Solution Explorer, and drag it onto the page. To add a user control to a Web Forms page in HTML view

In the Web Forms Designer, open the Web Forms page you want to add the control to, and then switch to HTML view. At the top of the page, before the <HTML> tag, add a directive that registers the control so it will be recognized when the page is processed. You use the directive to associate a name and a namespace with the Web user control by specifying TagPrefix, TagName, and Src location values. For example: <%@ Register TagPrefix="myNameSpace" TagName="myUserControl"

Src="userControl1.ascx" %> Put the directive in its own line. If there are no other directives, make it the first line in the file.

64

The values for the attributes in the Register directive are listed in the following table.

Attribute Description TagPrefix The TagPrefix determines a unique namespace for the user

control, so that if multiple user controls on the page happen to have the same name, they can be differentiated from each other. This will be the prefix to the control's name (such as <myNameSpace:xxx>) in the tag.

TagName The TagName is the name for the user control. This name is used in conjunction with the tag prefix to uniquely identify the namespace for your control, as in the following prefix:tagname element: <myNameSpace:myUserControl ... />

Src The Src attribute is the virtual path to the user control, for example "UserControl1.ascx" or "/MyApp/Include/UserControl1.ascx".

In the <BODY> portion of the file, create a tag for your control where you want

the control to appear. Use the TagPrefix and TagName you registered in Step 2. Give your control an ID and set the attribute runat=server, as in the following example:

<myNameSpace:myUserControl ID="mnuMain" runat="server" /> If your control has properties that you can set at design time, optionally set them by declaring their values in the tag: <myNameSpace:myUserControl ID="mnuMain" runat="server" selected="Login"

backColor="black" /> Proceed with designing the rest of your Web Forms page. You can switch to Design view to work with your page. The user control will be displayed using a glyph to indicate its location in the page, but will not display a WYSIWYG rendering in the designer. To edit the control, switch back to HTML view. Working with User Controls Programmatically

The public properties, methods, and events of a user control that is registered in a page are exposed to the parent Web Forms page. By simply adding a declaration for the user control to the code-behind class for the Web Forms page, you can work with the complete object model of the user control to your page's code.

To set a property of a user control in a Web Forms page

Select the user control file in Solution Explorer and drag it onto your page. Note the ID of the user control displayed in the page. Press F7 to switch from Design view to the code-behind file.

65

In the Declarations area, add a line to declare the user control. For example, for a user control of type WebUserControl1 whose ID is myControl1:

public class MyPage : System.Web.UI.Page { protected WebUserControl1 myControl1;

Note The ID in the code-behind declaration must exactly match the ID for the user control in Design view.

Now that you have a code declaration for the user control, all of the public properties, methods, and events of your user control are available. Write code to call methods or set properties of your user control. For example:

myControl1.Visible = true; myControl1.DataBind();

4.2 Web Custom Controls

Web custom controls are compiled components that run on the server and that encapsulate user-interface and other related functionality into reusable packages. They can include all the design-time features of standard ASP.NET server controls, including full support for Visual Studio design features such as the Properties window, the visual designer, and the Toolbox.

There are several ways that you can create Web custom controls:

• You can compile a control that combines the functionality of two or more existing controls. For example, if you need a control that encapsulates a button and a text box, you can create it by compiling the existing controls together.

• If an existing server control almost meets your requirements but lacks some required features, you can customize the control by deriving from it and overriding its properties, methods, and events.

• If none of the existing Web server controls (or their combinations) meet your requirements, you can create a custom control by deriving from one of the base control classes. These classes provide all the basic functionality of Web server controls, so you can focus on programming the features you need.

Note At design time in Visual Studio, your code always runs fully trusted, even if the code will eventually be in a project where it would receive less-than-full trust at run time. This means that your custom control might work properly when you are testing it on your own computer, but might fail due to lack of adequate permissions in a deployed application. Be sure to test your controls in the security context in which they will run in real-world applications.

66

Web user controls vs. custom controls If none of the existing ASP.NET server controls meet the specific requirements of

your applications, you can create either a Web user control or a Web custom control that encapsulates the functionality you need. The main difference between the two controls lies in ease of creation vs. ease of use at design time.

Web user controls are easy to make, but they can be less convenient to use in

advanced scenarios. You develop Web user controls almost exactly the same way that you develop Web Forms pages. Like Web Forms, user controls can be created in the visual designer, they can be written with code separated from the HTML, and they can handle execution events. However, because Web user controls are compiled dynamically at run time they cannot be added to the Toolbox, and they are represented by a simple placeholder glyph when added to a page. This makes Web user controls harder to use if you are accustomed to full Visual Studio .NET design-time support, including the Properties window and Design view previews. Also, the only way to share the user control between applications is to put a separate copy in each application, which takes more maintenance if you make changes to the control.

Web custom controls are compiled code (i.e. a class library), which makes them easier to use but more difficult to create; Web custom controls must be authored in code. Once you have created the control, however, you can add it to the Toolbox and display it in a visual designer with full Properties window support and all the other design-time features of ASP.NET server controls. In addition, you can install a single copy of the Web custom control in the global assembly cache and share it between applications, which make maintenance easier.

If your control has a lot of static layout, a user control might make sense. If your control is mostly dynamically generated — for instance rows of a data-bound table, nodes of a tree view, or tabs of a tab control — a custom control would be a better choice. The main differences between the two types are outlined in this table: Web user controls Web custom controls Easier to create Harder to create Limited support for consumers who use a visual design tool

Full visual design tool support for consumers

A separate copy of the control is required in each application

Only a single copy of the control is required, in the global assembly cache

Cannot be added to the Toolbox in Visual Studio

Can be added to the Toolbox in Visual Studio

Good for static layout Good for dynamic layout


Recommended