Simple Controls

Simple Controls

The simple controls are so named because most emit only a few lines of HTML. Some return client-side script too, but only under special circumstances. They re exceedingly easy to use, and thus are a great starting point for an exploration of Web controls.

TextBox Controls

TextBox controls are the ASP.NET equivalent of <input type= text/password > and <textarea> tags in HTML. Their purpose? To create text input fields in Web forms. The statement

<asp:TextBox  RunAt="server" />

creates a text input field in a Web form and assigns it the programmatic ID UserName . You can use a TextBox s Text property to declaratively insert text into a TextBox and also to read and write TextBox text from a server-side script. The following statement creates a TextBox that initially contains the string Elmo :

<asp:TextBox  Text="Elmo" RunAt="server" />

And the following server-side script reads the contents of the TextBox:

string name = UserName.Text;

Text is one of several public properties that the TextBox class exposes. Others include Rows and Columns, which size a TextBox by setting the number of rows and columns that it displays; MaxLength, which limits the number of characters a TextBox will accept; ReadOnly, which, when true, prevents the TextBox from accepting input; Wrap, which determines whether text wraps in a multiline TextBox; and TextMode, which can be set to SingleLine (the default) to create single-line input fields, MultiLine to create multiline input fields, or Password to create password input fields fields that display asterisks or other characters in place of the actual characters that the user types. The following statement creates a password input field named Password :

<asp:TextBox  TextMode="Password" RunAt="server" />

To create a multiline input field, set TextMode to MultiLine and Rows to the number of rows you want the TextBox to display:

<asp:TextBox  TextMode="MultiLine" Rows="10" RunAt="server" />

The Rows attribute is ignored unless you explicitly set TextMode to MultiLine.

A TextBox renders itself as an <input type= text >, <input type= password >, or <textarea> tag, depending on the value assigned to its TextMode property. Here are three <asp:TextBox> tags and the HTML that they produce:

// Before <asp:TextBox  RunAt="server" /> <asp:TextBox  TextMode="Password" RunAt="server" /> <asp:TextBox  TextMode="MultiLine" Rows="10" RunAt="server" /> // After <input name="UserName" type="text"  /> <input name="Password" type="password"  /> <textarea name="Comments" rows="10" ></textarea>

Examining the HTML that Web controls return is a great way to get acquainted with Web controls and learn more about how they work.

TextChanged Events and the AutoPostBack Property

TextBox controls fire TextChanged events following a postback if the text inside them has changed. An OnTextChanged attribute in an <asp:TextBox> tag designates a handler for TextChanged events:

<asp:TextBox  OnTextChanged="OnNameChanged" RunAt="server" /> . . . <script language="C#" runat="server"> void OnNameChanged (Object sender, EventArgs e) { // Name changed; read it from the TextBox string name = UserName.Text; } </script>

TextChanged events fire only when the page posts back to the server. By default, TextBox controls don t generate postbacks themselves and therefore fire TextChanged events only when another control on the page forces a postback. However, you can set a TextBox control s AutoPostBack property to true to force postbacks to occur (and TextChanged events to fire) the moment the text inside the control changes:

<asp:TextBox  OnTextChanged="OnNameChanged" AutoPostBack="true" RunAt="server" />

Unlike Windows edit controls, which fire EN_CHANGE notifications in response to each and every character that the user enters, TextBox controls with AutoPostBack enabled fire TextChanged events only when they lose the input focus (that is, when the user moves to another control in the Web page) following a text change. That s good, because a page that posts back to the server every time a character is entered into a TextBox would be a slow page indeed.

How does setting AutoPostBack to true cause postbacks to occur when a TextBox loses the input focus? With a sprinkle of JavaScript and a dash of Dynamic HTML (DHTML). Enter this statement into a Web form:

<asp:TextBox  AutoPostBack="true" RunAt="server" />

and the control outputs this:

<input name="UserName" type="text"  onchange="__doPostBack('UserName','')" language="javascript" /> . . . <script language="javascript"> <!-- function __doPostBack(eventTarget, eventArgument) { var theform = document.ctl0; . . . theform.submit(); } // --> </script>

The <input> tag includes an onchange attribute that activates a JavaScript function named __doPostBack on the client when the control loses the input focus following a text change. The __doPostBack function programmatically posts the page back to the server by calling the Submit method of the DHTML object that represents the form.

TextBox isn t the only Web control that features an AutoPostBack property; CheckBox, RadioButton, and several other controls support it as well. Whenever AutoPostBack appears in a control s property list, setting it to true causes postbacks to occur (and events to fire) the moment a change occurs in the state of the control. Otherwise, the control s events won t fire until an external stimulus forces a postback.

Label Controls

Label controls are among the simplest if not the simplest of all Web controls. They add programmable textual labels to Web forms. A Label control s Text property exposes the control text. The following statement adds Hello to a Web page:

<asp:Label Text="Hello" RunAt="server" />

A Label control declared this way renders itself to the Web page as a <span> tag:

<span>Hello</span>

Spans are benign HTML tags that are used to group other HTML elements.

Label controls frequently serve as placeholders for output written by server-side scripts. The following statement declares an empty Label control and assigns it the programmatic ID Output :

<asp:Label  RunAt="server" />

And this statement in a server-side script writes Hello to the Web page where the Label control is positioned:

Output.Text = "Hello";

Use a Label control whenever you want to add text to a Web page and change that text from a server-side script. For static labels, use ordinary HTML text instead. Static HTML text improves performance by preventing ASP.NET from having to instantiate and execute a control each time the page is requested from the server.

HyperLink Controls

HyperLink controls add hyperlinks to Web forms. HyperLink controls come in two forms: text hyperlinks and image hyperlinks. The following statement creates a hyperlink that renders itself as a text string and points to www.wintellect.com:

<asp:HyperLink Text="Click here" NavigateUrl="http://www.wintellect.com" RunAt="server" />

A slight modification transforms the hyperlink into an image that targets the same URL:

<asp:HyperLink ImageUrl="logo.jpg" NavigateUrl="http://www.wintellect.com" RunAt="server" />

Text hyperlinks render as <a href> tags; image hyperlinks render as <img> tags enclosed in <a href> tags. You normally include either a Text or an ImageUrl attribute in an <asp:HyperLink> tag, but not both. However, if you do specify both, the control uses the text you specify as a tool tip in supportive browsers.

The HyperLink class exposes a Target property that can be used to control how the targeted Web page is displayed. For example, the statement

<asp:HyperLink Text="Click here" Target="_new" NavigateUrl="http://www.wintellect.com" RunAt="server" />

opens the page in a new browser window. Any value that s valid for a Target attribute in an <a> tag is also valid in a HyperLink. Another use for Target attributes is to open pages in specific windows or frames.

Like Label controls, HyperLink controls should be used only when you want to change the properties of the control dynamically that is, when ordinary <a href> tags won t do. The following code initializes the target of a hyperlink when the page loads:

<asp:HyperLink  Text="Web page du jour" RunAt="server" /> . . . <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { MyLink.NavigateUrl = "www.wintellect.com"; } </script>

One motivation for initializing a HyperLink control in this way is to retrieve the targeted URL from a database or an XML file.

Image Controls

Image controls add images to Web forms by emitting <img> tags. Image s most important properties are ImageUrl, which specifies the URL of the image that the control renders; ImageAlign, which controls the alignment of the image; and AlternateText, which specifies the image s alternate text. Alternate text is displayed in place of the image in text-only browsers. The following statement declares an Image control in a Web form:

<asp:Image ImageUrl="logo.jpg" AlternateText="Company Logo" RunAt="server" />

Image controls are perfect for displaying images whose URLs are assigned at run time, possibly in response to user input. For static images, you can reduce overhead by using conventional <img> tags instead.

CheckBox Controls

CheckBox controls place check boxes in Web forms. (Surprise!) A CheckBox s Checked property determines whether the check box is checked (true) or unchecked (false), and its Text property controls the text displayed beside the check box. The following code declares a CheckBox control in a Web form:

<asp:CheckBox  Text="E-mail my confirmation" RunAt="server" />

And this server-side script determines whether the check box is checked when the form is submitted to the server:

if (Confirm.Checked) { // The box is checked } else { // The box is not checked }

On the off chance that you d like to reverse the positions of a check box and the text that normally appears to its right, include a TextAlign= Left attribute in the control tag.

CheckBox controls fire CheckedChanged events when they re checked and unchecked. By default, a CheckedChanged event doesn t fire the moment the check box is clicked; it waits until the page posts back to the server. To respond immediately to changes in a check box s state, set the control s AutoPostBack property to true to force postbacks:

<asp:CheckBox  Text="E-mail my confirmation" AutoPostBack="true" OnCheckedChanged="DoItNow" RunAt="server" /> . . . <script language="C#" runat="server"> void DoItNow (Object sender, EventArgs e) { // The check box was just checked or unchecked; do something! } </script>

Don t set AutoPostBack to true unless you really need CheckedChanged events to fire immediately. One justification for setting AutoPostBack to true is to dynamically change the contents of the page each time the check box is clicked.

RadioButton Controls

RadioButton controls create radio buttons in Web forms. Radio buttons present users with mutually exclusive lists of choices. Clicking a radio button checks that radio button and unchecks other radio buttons in the group.

RadioButton derives from CheckBox and therefore supports the same properties and events that CheckBox supports. It also adds a GroupName property for designating the group that a radio button belongs to. The following code declares five RadioButton controls and divides them into two groups: one group of three and another group of two. It also uses the RadioButton.Checked property to check the first radio button in each group:

<asp:RadioButton Text="Red"  Checked="true" GroupName="Colors" RunAt="server" /><br> <asp:RadioButton Text="Green"  GroupName="Colors" RunAt="server" /><br> <asp:RadioButton Text="Blue"  GroupName="Colors" RunAt="server" /><br> <br> <asp:RadioButton Text="Circle"  Checked="true" GroupName="Shape" RunAt="server" /><br> <asp:RadioButton Text="Square"  GroupName="Shape" RunAt="server" />

Grouping these controls by using the GroupName attribute is important because it tells the browser which radio buttons to uncheck when a radio button is checked.

Figuring out which radio button in a group of radio buttons is checked from a server-side script requires checking each button s Checked property one by one. A better way to add radio buttons to a Web page is to use a RadioButtonList. Its SelectedIndex property identifies the button that s checked. RadioButtonList also simplifies the task of arranging radio buttons on a page. You ll learn all about RadioButtonList later in this chapter.

Table Controls

Table controls add HTML tables to Web forms. They render a combination of <table>, <tr>, and <td> tags to browsers. Here s one way to add a table to a Web form:

<table> <tr> <td>Row 1, Column 1</td> <td>Row 1, Column 2</td> </tr> <tr> <td>Row 2, Column 1</td> <td>Row 2, Column 2</td> </tr> </table>

And here s the equivalent table created with a Table control:

<asp:Table  RunAt="server"> <asp:TableRow> <asp:TableCell>Row 1, Column 1</asp:TableCell> <asp:TableCell>Row 1, Column 2</asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell>Row 2, Column 1</asp:TableCell> <asp:TableCell>Row 2, Column 2</asp:TableCell> </asp:TableRow> </asp:Table>

Table controls add value to a Web form when you want to change a table s contents dynamically. For example, the following server-side script modifies the text in each of the table cells:

MyTable.Rows[0].Cells[0].Text = "Cell 1"; MyTable.Rows[0].Cells[1].Text = "Cell 2"; MyTable.Rows[1].Cells[0].Text = "Cell 3"; MyTable.Rows[1].Cells[1].Text = "Cell 4";

This script builds the entire table at run time:

<asp:Table  RunAt="server" /> . . . <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { for (int i=0; i<2; i++) { TableRow row = new TableRow (); for (int j=0; j<2; j++) { TableCell cell = new TableCell (); cell.Text = String.Format ("Row {0}, Column {1}", i + 1, j + 1); row.Cells.Add (cell); } MyTable.Rows.Add (row); } } </script>

These scripts work because a Table object exposes the rows that it contains through a property named Rows. Each row in the Rows collection is an instance of TableRow. Within a row, each cell is represented as a TableCell object that s accessible through the row s Cells collection. Calling Add on a Rows or Cells collection programmatically adds a row to a table or a cell to a row.

By default, a Table control s borders are invisible. You can change that by setting the control s GridLines property to Horizontal, Vertical, or Both. Other useful Table properties include CellPadding and CellSpacing, which, like the HTML attributes of the same name, control the spacing within and between cells, and BackImageUrl, which identifies a background image. Tables are often used in Web pages to paint colored backgrounds. To change a Table object s background color, use the BackColor property that Table inherits from WebControl.

Panel Controls

Panel controls serve as containers for other controls. One use for Panel controls is to control the visibility of a group of controls. The following Web form toggles four Label controls on and off by setting a Panel control s Visible property to true or false each time a check box is clicked. Note the AutoPostBack= true attribute in the <asp:CheckBox> tag:

<html> <body> <form runat="server"><br> <asp:CheckBox  Text="Show Labels" Checked="true" AutoPostBack="true" OnCheckedChanged="OnToggle" RunAt="server" /> <asp:Panel  RunAt="server"> <asp:Label Text="John" RunAt="server" /><br> <asp:Label Text="Paul" RunAt="server" /><br> <asp:Label Text="George" RunAt="server" /><br> <asp:Label Text="Ringo" RunAt="server" /><br> </asp:Panel> </form> </body> </html> <script language="C#" runat="server"> void OnToggle (Object sender, EventArgs e) { MyPanel.Visible = Toggle.Checked; } </script>

Another use for Panel controls is to specify horizontal alignment for a group of controls:

<asp:Panel HorizontalAlign="Center"  RunAt="server"> <asp:Label Text="John" RunAt="server" /><br> <asp:Label Text="Paul" RunAt="server" /><br> <asp:Label Text="George" RunAt="server" /><br> <asp:Label Text="Ringo" RunAt="server" /><br> </asp:Panel>

Panel controls render as HTML <div> tags. Therefore, it s appropriate to use them any time you would ordinarily use a <div> tag but want to change the attributes of that tag dynamically.



Programming Microsoft  .NET
Applied MicrosoftNET Framework Programming in Microsoft Visual BasicNET
ISBN: B000MUD834
EAN: N/A
Year: 2002
Pages: 101

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net