Web Controls


All server control classes inherit either directly or indirectly from the System.Web.UI.Control base class. The HTML controls inherit indirectly through the System.Web.UI.HtmlControls.HtmlControl class. The other type of ASP.NET server controls, the Web controls, inherit from the Control base class through a different common base class: System.Web.UI.WebControls.WebControl. The Web controls are a richer set of controls than the HTML server controls. Because both types of controls are server controls, they have the same fundamental capabilities:

  • They expose events unique to the control, for which the developer can provide handlers.

  • They automatically manage ViewState so that user input is maintained between requests.

  • They participate in the page and control life cycle, allowing them to be manipulated dynamically in code.

Web controls offer even more than their familiar HTML element counterparts. For example, validation controls simplify the process of checking user input. Other Web controls display lists of data as well as bind to record sets from a database. In addition to user interaction controls such as the Button and Textbox controls are more sophisticated controls such as Calendar and AdRotator.

Code Listing 2-4 demonstrates how a Web control can produce advanced rendering and provide events for interacting with the user. In this example, the Label and Calendar Web controls are placed inside an HTML form server control. You’ll also notice an event handler for the calendar’s SelectionChanged event. In the event handler, we simply change the text of the label to display the newly selected date.

Code Listing 2-4: Calendar.aspx

start example
 <%@Page language="C#" %>
<script runat="server">
protected void Calendar_Changed(object o, EventArgs e) {
theLabel.Text = "You selected " +
theCalendar.SelectedDate.ToShortDateString();
}
</script>
<form runat="server">
<asp:label runat="server"
text="select a date" />
<asp:calendar runat="server"
OnSelectionChanged="Calendar_Changed" />
</form>
end example

Figure 2-2 shows the page before and after a date has been selected. The calendar user interface (UI) as well as the logic for navigating between months is produced by the Web control. These updates are accomplished transparently during automatic postbacks to the server that occur when the user makes a selection. Notice that we didn’t include a button in the form for submitting the calendar. The calendar days and month navigation UI render as links that submit the form.

click to expand
Figure 2-2: A page before and after selecting a date

ASP.NET Web Control Hierarchy

We’ve mentioned the different types of ASP.NET Web controls and pointed out that they inherit from a common base class. Figure 2-3 shows the inheritance hierarchy. Notice again that the Web controls are more focused on functional elements for Web development than the HTML server controls and familiar client-side elements.

click to expand
Figure 2-3: ASP.NET Web control hierarchy

Three controls in Figure 2-3—BaseValidator, BaseDataList, and the ListControl—are abstract classes used to encapsulate functionality for the derived types. As such, they can’t be instantiated directly. The functionality for each of these controls is apparent from their names, so we won’t go into details in this chapter. We do, however, discuss the list controls and validator controls in more detail, and Chapter 3 is devoted to the data controls.

Leveraging User Controls

As you can see, the ASP.NET Web controls provide a set of fundamental building blocks for building dynamic Web applications. You can also use them to build more complex functionality for the entire site. ASP.NET provides a simple means for encapsulating groups of controls in the user control model. User controls are constructed just like ASPX pages, with event handlers and a control tree, but they utilize the .ASCX file extension and aren’t requested directly by the user. Instead, they are included in the ASPX page like a server control and are used as larger building blocks comprised of server controls for application development. They provide a simple way to encapsulate a piece of functionality created with other controls such that they can be re-used. User controls can expose properties, methods, and events just like a server control but can be created declaratively instead of requiring you to compile a separate control inheriting from Control or WebControl.

Code Listing 2-5 is a user control that we can use in other pages as a footer to display the time. Although the code is simple, including the code and set of controls on many pages without encapsulating it all as a user control might be tedious—particularly if you had to change the footer—because you’d have to edit each page, cutting and pasting changes in numerous files. It would be an error-prone and unpleasant task at best. The user control allows you to centralize code and control declarations for re-use.

Code Listing 2-5: CurrentTime.ascx

start example
 <script runat="server" language="c#">
protected void Page_Load(object o, EventArgs e) {
timeLabel.Text = DateTime.Now.ToString();
}
</script>
<center>
<b>
<asp:label runat="server" style="color:red" />
</b><br/>
<i>Time brought to you by ASP.NET Coding Strategies</i>
</center>
end example

By encapsulating the functionality in an ASCX file, we can utilize it in multiple ASPX pages. Changes to the user control are reflected in all pages that contain it. Code Listing 2-6 shows how to incorporate this user control in a page.

Code Listing 2-6: IncludeCurrentTime.aspx

start example
 <%@Register TagPrefix="CodingStrategies" TagName="Time" 
src="/books/2/540/1/html/2/CurrentTime.ascx" %>
<form runat="server">
page content goes here <br />
followed by the user control <br />
<CodingStrategies:Time runat="server" />
</form>
end example

Tip

Remember that updating a user control will cause the compiled pages that reference the user control to become invalidated. When the pages are next requested, they will have to be recompiled.

Not only does the ASCX file offer us the advantage of encapsulating pieces of the application into reusable pieces—it also allows us to cache user controls separately. Chapter 6 has more details about utilizing the cache, but it’s important to note here that user controls support the OutputCache directive. In particular, read-only views of data in multiple pages of an application can benefit from being placed in a user control that is temporarily cached independently from the containing page because doing so reduces trips to the database.

The encapsulation in user controls goes beyond just including content from somewhere else in the page. We can provide public properties, fields, and methods on the user control that can be used from the page that utilizes the user control. In addition, we can hide members of the user control from the containing page by setting the member-access modifiers. However, remember that the controls themselves are in the control tree, and the page code is free to manipulate them at will. The user control in Code Listing 2-7 provides a public property setter that updates the color it is displaying.

Code Listing 2-7: FavoriteColor.ascx

start example
 <%@Import namespace="System.Drawing" %>
<script runat="server" language="C#">
protected Color favoriteColor = Color.Black;
protected void Page_Load(Object o, EventArgs e) {
theLabel.Text = favoriteColor.Name;
}
public Color Color {
set {
favoriteColor = value;
theLabel.Text = favoriteColor.Name;
theLabel.ForeColor = favoriteColor;
}
}
</script>
<h2><asp:label runat="server"/></h2>
end example

Code Listing 2-8 shows the page that uses the user control. In it, the user is given a text box to enter a favorite color. The name provided by the user is then turned into a color structure and set on the FavoriteColor user control.

Code Listing 2-8: SetFavoriteColor.aspx

start example
 <%@Import Namespace="System.Drawing" %>
<%@Register TagPrefix="CodingStrategies" TagName="Color"
src="/books/2/540/1/html/2/FavoriteColor.ascx" %>
<script language="C#" runat="server">
protected void SetColor(object o, EventArgs e) {
Color color = Color.FromName(theTextbox.Text);
colorControl.Color = color;
}
</script>
<form runat="server">
Name your favorite color
<asp:textbox runat="server"
OnTextChanged="SetColor" Value="Black"/><br />
Your favorite color is:
<CodingStrategies:Color runat="server"
/><br />
<asp:button type="submit" runat="server" Text="Go" />
</form>
end example

Note

The members of a user control in the output cache can’t be accessed from pages that contain the control. The output of the cached control will be included in the page, but the user control object itself will not be available. Attempting to access it will result in an error message.

start sidebar
Extending Web Controls

In addition to using the HTML server controls and the Web controls, you can create your own controls. You can also choose from among an impressive market of third-party controls that provide features not included in ASP.NET.

You can choose to inherit directly from Control or indirectly via the WebControl class. We won’t begin to cover the topic of writing your own controls in this book, but we can recommend another title, Developing Microsoft ASP.NET Server Controls and Components by Nikhil Kothari and Vandana Datye (Microsoft Press, 2002) to help you. The book covers in great detail the control architecture and how to take advantage of it, and it includes information on providing design-time behavior to enhance the developer’s work when using the control from Microsoft Visual Studio or another developer tool.

end sidebar

Debugging ASP.NET applications is covered in Chapter 10, but we’ll examine one related topic here. Developers frequently look for quick ways to simply output a message. A typical way of doing this in Web development is to use the browser to display a message box, which the user dismisses to continue interacting with the page. Developers often get accustomed to the ease provided by the user controls, and find in the documentation a MessageBox object. However, when you create one of these controls in code (as you would on the client) and try to display it, nothing shows up. The .NET Framework has a MessageBox object, but when you call its Show method in an ASPX page, the system tries to show the object on the server, not on the client.

Code Listing 2-9 demonstrates including a client-side message box. We have a server-side method named CreateClientSideMessageBox that takes a single string parameter. It writes out the JavaScript code in the output to invoke the browser’s alert method by using the string message passed in to the server- side method. This alert method causes a client-side message box to be displayed, instead of showing a message box on the server. Notice that we separate the last line of the script block. The /s is an escape sequence that can cause a compilation failure, so we concatenate the strings to avoid the issue.

Code Listing 2-9: Alert.aspx

start example
 <script language="C#" runat="server">
protected void Page_Load(object o, EventArgs e) {
if(IsPostBack) {
CreateClientSideMessageBox("IsPostBack is true");
}
else {
CreateClientSideMessageBox("IsPostBack is false");
}
}

protected void CreateClientSideMessageBox(string message) {
Response.Write("<script language=\"javascript\">");
Response.Write("alert(\"" + message + "\");");
Response.Write("</" + "script>");
}
</script>

<form runat="server">
this page displays a client side message box<br/>
<asp:button runat="server" Text="go" />
</form>
end example

Note

If you have to import the System.Windows.Forms namespace into your page or Microsoft Visual Studio .NET Web application project, chances are your code is using server-side resources that have no visible desktop on which to be displayed. Thus, they must be disposed of to avoid introducing resource issues under heavy load. Verify that you are not mistakenly trying to display UI elements on the server.

In Web applications, users commonly interact with a list of items. Four ASP.NET list controls inherit from the abstract ListControl base class. They differ in the user interface presented to the user and in the constraints that they offer. The list controls contain a collection of ListItem objects that can be data-bound (discussed in more detail in Chapter 3) or set directly as the inner text of the list controls. You can also create the list items dynamically and add them to the control’s Items collection. When the value property of an item is not set explicitly, that control’s value will default to the Text property of the control. Let’s compare the different types of list controls and the way the data is presented to the user.

The list items in a CheckBoxList are presented as check boxes. Multiple items from the list can be selected at the same time. In Code Listing 2-10, the CheckBoxList is populated declaratively. The control tracks which items are selected, allowing us to provide an event handler that is fired when the selected items are changed and posted back to the server; that is, the code reacts only when the user takes action that changes the selected items in the list. In the handler for the SelectedIndexChanged event, we iterate over all items in the list and output all that are selected. The code does not clear previous collections, leaving it to the user to add and remove items at will. The ViewState management keeps track of the selected items between requests and automatically restores them to their selected state during the next rendering.

Code Listing 2-10: CheckBoxList.aspx

start example
 <script language="C#" runat="server">
protected void CheckBoxListSelectionChanged(
object o, EventArgs e) {
bool valueSet = false;
foreach(ListItem item in languageCheckBoxList.Items) {
if (item.Selected) {
if(valueSet) {
favoriteLanguage.Text += ", " + item.Text;
}
else {
favoriteLanguage.Text = item.Text;
valueSet = true;
}
}
}
}
</script>
<form runat="server">
<asp:CheckBoxList runat="server"
OnSelectedIndexChanged="CheckBoxListSelectionChanged" >
<asp:ListItem runat="server">C#</asp:ListItem>
<asp:ListItem runat="server">VB.NET</asp:ListItem>
<asp:ListItem runat="server">JScript.NET</asp:ListItem>
</asp:CheckBoxList><br/>
Favorite Language:
<b><asp:label runat="server"
style="color:blue" Text="Not Set" /></b><br />
<asp:button runat="server" Text="Submit"/>
</form>
end example

Notice in Code Listing 2-10 that we iterate over the collection of items in the OnSelectedIndexChanged event handler to ascertain the complete set of selected values.

Tip

If the user interface supports mulle simultaneous selections, accessing SelectedItem, SelectedIndex, and SelectedValue will return the first item the control finds when it iterates over the items. To get the complete set of selected items, loop through all items from the list.

ListBox

The ListBox control, like CheckBoxList, also supports multiple simultaneous selections on the part of the user, but these can be restricted to a single selection by setting the SelectionMode property to the Single value of the ListSelectionMode enumeration. In Code Listing 2-11, the set of languages in Code Listing 2-10 is in our list again, but this time we add the list items to the ListBox dynamically in the Page_Load event. Notice that we need to add the items only in the initial request. The set of items is restored automatically from ViewState during postbacks.

Code Listing 2-11: ListBox.aspx

start example
 <script language="C#" runat="server">
protected void Page_Load(object o, EventArgs e) {
if(!IsPostBack) {
ListItem item;
item = new ListItem("C#");
languageListBox.Items.Add(item);
item = new ListItem("VB.NET");
languageListBox.Items.Add(item);
item = new ListItem("JScript.NET");
languageListBox.Items.Add(item);
languageListBox.Rows = 3;
}
}

protected void ListBoxSelectionChanged(object o, EventArgs e) {
bool valueSet = false;
foreach(ListItem item in languageListBox.Items) {
if (item.Selected) {
if(valueSet) {
favoriteLanguage.Text += ", " + item.Text;
}
else {
favoriteLanguage.Text = item.Text;
valueSet = true;
}
}
}
}
</script>
<form runat="server">
<asp:ListBox runat="server"
SelectionMode="multiple"
OnSelectedIndexChanged="ListBoxSelectionChanged" /><br />
Favorite Language: <b>
<asp:label runat="server"
style="color:blue" Text="Not Set" /></b><br />
<asp:button runat="server" Text="Submit"/>
</form>
end example

We set the Rows property to the number of items from the list. Of course, this wouldn’t be a suitable approach when the list contains a lot of items because the Rows property corresponds to the number of items from the list that are displayed without scrolling. Vertical scroll bars are provided automatically when the number of items in the list exceeds the row count.

Tip

Items added to a list control are carried between client and server in ViewState. If the set of items is a significant size, consider disabling ViewState. That way the control will not bloat the payload by unnecessarily carrying the ViewState in a round trip between client and server. In this case, be aware that the selected items are no longer available, so you must provide code to ascertain when the selected items were changed.

DropDownList

The DropDownList provides a compact approach for selecting a single item from a list. In the other lists, you start with a default of no selection, but the DropDownList differs in that an item from the list is always selected. In Code Listing 2-12, we use the previous example of selecting a favorite language but instead use the DropDownList, explicitly initializing the label of the selected language with the selected item. Even though we didn’t set the Selected property of any item in the list, the first item added takes on this value.

Also important to note in Code Listing 2-12 is that the text of a ListItem is set to the content of the Value attribute only when a value is not specified in the body of the ListItem. In DropDownList.aspx, we set unique values and display those instead. Doing this is particularly useful when working with database back ends in which the friendly text displayed to the user might be only a convenience and the important field is available as the ListItem value.

Tip

To create a drop-down list that does not appear to have an initially selected value, add an item to the top of the list that is selected by default and corresponds to no user selection.

Code Listing 2-12: DropDownList.aspx

start example
 <script language="C#" runat="server">
protected void Page_Load(object o, EventArgs e) {
if(!IsPostBack) {
ListItem item;
item = new ListItem("C#", "1");
languageDropDownList.Items.Add(item);
item = new ListItem("VB.NET", "2");
languageDropDownList.Items.Add(item);
item = new ListItem("JScript.NET", "3");
languageDropDownList.Items.Add(item);

favoriteLanguage.Text
= languageDropDownList.SelectedItem.Value;
}
}

protected void DropDownListSelectionChanged(object o, EventArgs e) {
favoriteLanguage.Text
= languageDropDownList.SelectedItem.Value;
}
</script>
<form runat="server">
<asp:DropDownList runat="server"
OnSelectedIndexChanged="DropDownListSelectionChanged" >
</asp:DropDownList><br/>
Favorite Language: <b>
<asp:label runat="server"
style="color:blue" /></b><br />
<asp:button runat="server" Text="Submit"/>
</form>
end example

RadioButtonList

The RadioButtonList control, like the DropDownList control, provides an interface for the user to select a single item from a list. With this rendering, the user is presented with a set of radio buttons from which to make a single selection. When an item is selected, the previously selected item is cleared. The SelectedIndexChanged event is not fired until the form is posted back to the server. The user is thus free to change the value on the page without invoking the server- side handler until some other action on the page causes a postback.

Code Listing 2-13 is another example of selecting a favorite language. Notice that we do not try to access the SelectedItem property of the RadioButtonList control until the SelectedIndexChanged event handler. Until the user makes a selection, or SelectedIndex is set explicitly in code, the SelectedItem property is null.

Code Listing 2-13: RadioButtonList.aspx

start example
 <script language="C#" runat="server">
protected void Page_Load(object o, EventArgs e) {
if(!IsPostBack) {
ListItem item;
item = new ListItem("C#", "1");
languageRadioButtonList.Items.Add(item);
item = new ListItem("VB.NET", "2");
languageRadioButtonList.Items.Add(item);
item = new ListItem("JScript.NET", "3");
languageRadioButtonList.Items.Add(item);
}
}

protected void DropDownListSelectionChanged(object o,
EventArgs e) {
favoriteLanguage.Text
= languageRadioButtonList.SelectedItem.Value;
}
</script>
<form runat="server">
<asp:RadioButtonList
runat="server"
OnSelectedIndexChanged="DropDownListSelectionChanged" >
</asp:RadioButtonList><br/>
Favorite Language: <b>
<asp:label runat="server"
style="color:blue" /></b><br />
<asp:button runat="server" Text="Submit"/>
</form>
end example

Figure 2-4 shows the default appearance of the four ASP.NET list controls. Each is filled with the sample set of .NET Framework languages used in the previous examples in this chapter.

click to expand
Figure 2-4: Rendering of the ASP.NET list controls




Microsoft ASP. NET Coding Strategies with the Microsoft ASP. NET Team
Microsoft ASP.NET Coding Strategies with the Microsoft ASP.NET Team (Pro-Developer)
ISBN: 073561900X
EAN: 2147483647
Year: 2005
Pages: 144

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