Building Microsoft ASP.NET Applications for Mobile Devices, Second Edition [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Building Microsoft ASP.NET Applications for Mobile Devices, Second Edition [Electronic resources] - نسخه متنی

Andy Wigley; Peter Roxburgh

نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
افزودن یادداشت
افزودن یادداشت جدید






The ObjectList Control

The ObjectList control is a very flexible control. Its primary purpose is to display a single field from the data source to the user as the initial list of items, and then when the user selects an item, it displays many more fields from the selected data record (the detail display). In addition, the ObjectList control offers much more flexibility in the commands that you can associate with each item. When it displays the detail view, it can also display a menu of options which you can customize to offer unique menu options depending on which item from the initial list the user selected. You can choose to display all the fields in the data record, or a subset of the fields.

Like the List control, the ObjectList control supports internal paging, meaning that it's useful for displaying larger lists of items. The ObjectList control also supports templating, making it very flexible and able to implement device-specific behavior. (You'll learn more about templating in Chapter 10.) Unlike the SelectionList and List controls, you can't supply the data of an ObjectList control as static data items; instead, the ObjectList must be data bound.


Syntax


The following listing shows the server control syntax used to code the ObjectList control. The LoadItems event and ItemCount property are inherited from the PagedControl parent class; you use these only when you implement custom pagination. (See the section "Custom Pagination," earlier in this chapter, for more details.) <Field> items are used to explicitly declare named fields from the source data set to display. Usually, you use these if you have AutoGenerateFields set to False, although you can use them together (see Table 6-4 below for more information on these properties). You use <Command> tags to declare item commands that are displayed along with the details of a selected item. (See the section "Providing More Than One Command for Each Item," later in this chapter.)

<mobile:ObjectList
runat="server"
id="id"
Alignment="{NotSet|Left|Center|Right}"
BackColor="backgroundColor"
Font-Bold="{NotSet|False|True}"
Font-Italic="{NotSet|False|True}"
Font-Name="fontName"
Font-Size="{NotSet|Normal|Small|Large}"
ForeColor="foregroundColor"
StyleReference="StyleReference"
Wrapping="{NotSet|Wrap|NoWrap}"
AutoGenerateFields="{True|False}"
CommandStyle="StyleReference"
DataMember="dataMember"
DataSource="dataSource"
DefaultCommand="onDefaultCommandHandler"
ItemCount="itemCount"
LabelField="fieldname"
LabelStyle="StyleReference"
OnItemDataBind="onItemDataBindHandler"
OnItemCommand="onItemCommandHandler"
OnLoadItems="loadItemsHandler">
OnShowItemCommands="onShowItemCommandsHandler"
TableFields="tableFields">
<!-- Optional explicitly declared fields -->
<Field
id="id"
Title="titleText"
DataField="value"
FormatString="formatString"
Visible="{True|False}" />
</Field>
<!-- Optional explicitly declared commands -->
<Command Name="CommandName" Text="CommandText" />
</mobile:ObjectList>


Properties and Events


Table 4-1 and Table 4-2 for details of those properties that are inherited from MobileControl.) The Type column describes the type of the property when setting or getting the property in code. Refer to the preceding "Syntax" section for valid values when setting the property in server control syntax.














































































Table 6-4: Significant Properties and Events of the ObjectList Control


Property/ Event


Type


Description


AllFields


System.Web.UI. MobileControls. ObjectListFieldCollection


This property returns an ObjectListFieldCollection object, which contains a System.Web.UI. MobileControls. ObjectListField object for each data source field added to the ObjectList control, whether automatically generated or explicitly defined (through a <Field> tag or added in code through the Fields property). This collection is available only after data binding. You can't add or remove fields from this collection; however, you can manipulate the properties of the contained fields.


AutoGenerateFields


True|False


Configures the control to displays all the fields from the source DataSet object. Field labels (displayed on the details screen) default to the FieldName property. You'll need to set the LabelField property so that the application uses the correct field as the primary list index.


BackCommandText


String


Sets or gets the text used for the navigation link to return from the Details view to the List view. Default is "Back" (or localized equivalent).


Commands


System.Web.UI. MobileControls. ObjectList-Command-Collection


Returns the ObjectListCommandCollection object. There is an ObjectListCommand object in this collection for each item command that you define using <Command> tags or that you add in code. See the section "Providing Different Commands for Different List Items," later in this chapter, for an example of manipulating this collection.


CommandStyle


Valid Style in StyleSheet


Sets the style used to display item commands on the client device. This property is not persisted between client requests, so you must set it on every request. The easiest way to do this is to define it in server control syntax.


DataMember


String


Used only when the control is data bound to a DataSet or DataTable object. This property specifies the name of the table in the DataSet to which the control should bind.


DataSource


Object


The DataSet object or enumerated collection that is the data source.


DefaultCommand


String


By default, the list displays the value of the field specified by the LabelField property as a hyperlink. Selecting the link takes the user to another screen that displays additional fields for that item. However, if the code defines a DefaultCommand property, selecting an item from the list invokes the OnItemCommand event handler with this property's value. You can still access the item details through a More or More Details link, which appears alongside links for any other item commands you might have defined. (See the ItemCommand description in this table for more information.)


Details


System.Web.UI. MobileControls.Panel


Gets the Panel control that is used to display the item details. This property is particularly useful when you've implemented an <ItemDetailsTemplate> and want to set properties of a control that you've placed in the template. To locate the control, you use this syntax:

ObjectList1.Details.FindControl("controlID")


DetailsCo mmandText


String


Sets or gets the text used for the link that displays the Details view. DetailsCommandText is used only on WML browsers.


Fields


ObjectListFieldCollection


Similar to AllFields. Fields returns an ObjectListFieldCollection object, which contains an ObjectListField object for each data source field added to the ObjectList control that has been explicitly defined (through a <Field> tag or added in code through the Fields property). Unlike the AllFields collection which is read-only, you can add or remove fields from this collection using methods of the ObjectListFieldCollection object.


ItemCount


Integer


You use this property with custom pagination. It specifies the total number of items in the source dataset. To use custom pagination, you must set the Form.Paginate property to True.


LabelField


String


Specifies the name of the field in the data source you'll use as the primary index. The primary index provides the list from which users make their initial selection. The LabelFieldIndex property does the same thing but by specifying the index into the AllFields collection.


LabelStyle


String


Sets the style used to display the header label. LabelStyle isn't persisted between client requests, so you must set it on every request. The easiest way to do this is to define it in server control syntax.


MoreText


String


Sets or gets the text used for the More link on HTML browsers. See the description of the TableFields property for situations where a More link is displayed.


SelectedIndex


Integer


Gets or sets the index of the selected item.


Selection


System.Web.UI. MobileControls. ObjectListItem


Gets the selected item or null if there is no selection.


TableFields


String; a list of field names separated by semicolons


If you don't specify TableFields (the default), the application presents the list as a single column that consists solely of the value contained in the field specified by the LabelField property. If you specify a DefaultCommand property and the device supports tables, that single column will consist of both the value of the LabelField property and a More link. If you define the TableFields property, the application presents each item in the list in a table (if the device supports tables), with the columns defined by the fields identified in this property. A More column allows access to a view that shows all the fields for the item.


ViewMode


System.Web.UI. MobileControls. ObjectListViewMode enumeration: List|Commands|Details


Allows you to set the desired ObjectList views displayed. List view is the initial item list. The Details view shows the details of the selected item. The Commands view is displayed only on small-screen browsers such as those on mobile phones and is the first screen displayed after the user has made a selection; it displays a menu of options consisting of any item commands (such as those you have defined with <Command> tags) plus a link to the Details view (as shown on the right-hand image in Figure 6-9). The user must make a selection from the list the ObjectList first displays before you are allowed to set the ViewMode property to Commands or Details.


ItemCommand (Event)


Event handler method name


Specifies the event handler the code calls when the user selects a command associated with an item's detail display. You define commands using the <Command> element or by manipulating the collection exposed through the Commands property. The event handler method must have a signature of eventHandlerMethodName(object source, System.Web.UI.MobileControls. ObjectListCommandEventArgs e).


LoadItems (Event)


Event handler method name


Required when you specify an ItemCount property, thus enabling custom pagination. The application calls this event handler each time the runtime requires new data. This allows you to pass display data to the control as needed, rather than passing all of the data up front.


ShowItemCommands (Event)


Event handler method name


Specifies the event handler to call when the detail of an item must be displayed and the application is formulating the command links to display alongside the details (such as those defined using <Command> tags). In this event handler, you can create or delete commands, thus building a list of commands specific to the item to be displayed.



Using the ObjectList Control


Like the List control, the ObjectList control supports internal pagination. The List control allows you to define items statically or add them programmatically, and you can bind it to a dataset. The ObjectList control, however, must be bound to a data source.

As mentioned, the ObjectList control offers many more capabilities than the List control. Here is a list of the things you can do with the ObjectList control that you can't do with the other list controls:



Displaying multiple fields from the data sourceThe List control and SelectionList control can display only a single field from the source.



Displaying the items in a table, rather than in a single-column listThe initial list can display more than one field from the source, but this is supported only on HTML browsers.



Providing more than one command for each itemThe List control can handle only a single command action, which it applies to all items. The ObjectList control can do this too, but it also offers a number of command options associated with each item.



Providing different commands for different list itemsThis capability is similar to a context menu that you can program to display a different set of item commands to users, depending on which list item they select.



Displaying a single field, with multiple fields as a secondary functionAlthough displaying the details of a selected item is no longer the list's primary purpose, it's still available to users as a secondary function.



In the following sections, you'll learn how to implement each of these scenarios.

Displaying Multiple Fields from the Data Source


The data records in the data source to which you bind the ObjectList consists of a number of fields. One of the fields is displayed as the Label field—that is, the field that is displayed as a link in the initial list. When the user selects an item in the initial list, the application directs him or her to a second screen that displays the full set of fields for the item, as Figure 6-7 shows.


Figure 6-7: Using the ObjectList control to display multiple fields of an item in a dataset. Selecting an item shows all its fields.

You have two ways to select which fields will be displayed. First, you can set the AutoGenerateFields property to true. (This is the default.) This setting takes each field in the source DataSet and displays it, using the field name as the label. One of the fields will be the Label field, which will be displayed as the initial link. Often, this won't be the field you want as the initial link. Therefore, you must set the LabelField property to the name of the field that you want to use as the primary selection field.

The second way you can select the fields to be displayed is by setting the AutoGenerateFields property to false. Instead of automatically generating the fields to be displayed, you define them yourself. The easiest way to do this is to define these fields statically in the mobile Web Forms page by using the field declaration syntax, as you can see in the following example:

    <Field 
id="Teamname" <!-- Programmatic ID of field -->
Title="Team" <!-- Label text -->
DataField="TeamName" <!-- Field name -->
FormatString=" <!-- ToString() format string -->
Visible="true" /> <!-- true or false -->
</Field>

The Title attribute specifies a label to use instead of the FieldName, the DataField attribute specifies which source field to use, and the Visible attribute enables and disables a particular field's display. By default, the field is displayed by calling its ToString method with no format modifier. If this isn't suitable, use FormatString to specify an alternative conversion. FormatString uses the rules defined by the System.String.Format method. For example, to format a numeric value as a currency string, set the FormatString attribute to "{0:c}".Consult the Microsoft .NET Framework SDK documentation for details.

Whether you let the display fields generate automatically or you define them yourself in the .aspx file, the result is a collection of field definitions stored in an ObjectListFieldsCollection object. You can retrieve this collection by using the AllFields property of the ObjectList class, accessing the ObjectListField objects from the collection, and then manipulating the properties.

For example, the following code fragment shows how to set the Visible property of the ObjectListField object for the Played field:

foreach (ObjectListField oblFld in myObjectList.AllFields)
{
if (oblFld.DataField == "Played") oblFld.Visible = false;
}

You can also access the ObjectListField object directly if you know the index for the collection of the field you want, as shown here:

myObjectList.AllFields[3].Visible = false;

Listings 6-11 and 6-12 show an ObjectList object that's bound to a control that's bound to a data collection stored in an ArrayList object. The TeamStats class defines the data records this sample uses and has seven properties. The LabelField property is the TeamName field, which is displayed as the primary index for the user. You could set the AutoGenerateFields property to true and display all the properties of the source data record (a TeamStats instance), but instead, the sample explicitly declares <Field> items to display the TeamName, Won, Drawn, Lost, and Points properties of the source.

Listing 6-11: Source for ObjectListExample.aspx






<%@ Page Inherits="MSPress.MobWeb.ObjListEx.MyWebForm" Language="c#" 
CodeBehind="ObjectListExample.aspx.cs" AutoEventWireup="False" %>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<mobile:Form runat="server" >
<mobile:Label runat="server" StyleReference="title">
Season 2003 results</mobile:Label>
<mobile:ObjectList id="ObjectList1" runat="server">
AutoGenerateFields="false">
<Field Title="Team" DataField="TeamName"></Field>
<Field Title="Won" DataField="Won"></Field>
<Field Title="Drawn" DataField="Drawn"></Field>
<Field Title="Lost" DataField="Lost"></Field>
<Field Title="Pts" DataField="Points" Visible="false"></Field>
</mobile:ObjectList>
</mobile:Form>












Listing 6-12: Code-behind module ObjectListExample.aspx.cs






using System;
using System.Collections;
using System.Web.UI.MobileControls;
namespace MSPress.MobWeb.ObjListEx
{
public class MyWebForm : System.Web.UI.MobileControls.MobilePage
{
protected ObjectList ObjectList1;
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
private void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
ArrayList array = new ArrayList();
array.Add(new TeamStats("Dunes",1,38,24,8,6,80));
array.Add(new TeamStats("Phoenix",2,38,20,10,8,70));
array.Add(new TeamStats("Eagles",3,38,20,9,9,69));
array.Add(new TeamStats("Zodiac",4,38,20,8,10,68));
ObjectList1.DataSource = array;
ObjectList1.LabelField = "TeamName";
ObjectList1.DataBind();
}
}
}
class TeamStats
{
private String _teamName;
private int _position, _played, _won, _drawn, _lost, _points;
public TeamStats(String teamName,
int position,
int played,
int won,
int drawn,
int lost,
int points)
{
this._teamName = teamName;
this._position = position;
this._played = played;
this._won = won;
this._drawn = drawn;
this._lost = lost;
this._points = points;
}
public String TeamName { get { return this._teamName; } }
public int Position { get { return this._position; } }
public int Played { get { return this._played; } }
public int Won { get { return this._won; } }
public int Drawn { get { return this._drawn; } }
public int Lost { get { return this._lost; } }
public int Points { get { return this._points; } }
}
}











Displaying the Items in a Table


The TableFields property defines which fields appear in the initial list. By default, this property is a blank string, meaning that it will display only the field the LabelField property indicates. If you provide a list of field names separated by semicolons, the runtime will attempt to render a table displaying the requested fields, subject to the client's ability to support tables. This will override any LabelField setting. Furthermore, the first field in the list becomes the link—either to show all the item fields or, if you specify a DefaultCommand property, to invoke the OnItemCommand event handler for the default command. Figure 6-8 offers an example of the output.


Figure 6-8: An HTML browser supports table output, but a WML browser displays a single-column list. In both cases, all fields are displayed when you select the link.

The code-behind module for the .aspx file shown in Listing 6-13 is identical to that shown in Listing 6-12, apart from the change of the namespace to MSPress.MobWeb.ObjListTblEx, so we don't show it here.

Listing 6-13: Source for ObjectListTableExample.aspx






<%@ Page Inherits="MSPress.MobWeb.ObjListTblEx.MyWebForm" Language="c#" 
CodeBehind="ObjectListTableExample.aspx.cs" AutoEventWireup="False" %>
<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<mobile:Form runat="server"
<mobile:Label runat="server" StyleReference="title">
Season 2003 results</mobile:Label>
<mobile:ObjectList id="ObjectList1"
runat="server"
AutoGenerateFields="true"
TableFields="TeamName;Position;Points">
</mobile:ObjectList>
</mobile:Form>












Providing More Than One Command for Each Item


The List control allows only a single command for each item. The List control raises the ItemCommand event when the user selects an item from the list.

The ObjectList control allows you to associate as many commands as you want with each item (we'll call them item commands). After the user selects an item from the initial list, the control displays all the other properties of the item. On HTML browsers, any item commands that you specify will be displayed at the foot of that page. On WML browsers, the item commands appear on an intermediate page, which is displayed after the user selects an item. Figure 6-9 illustrates this. (The code for this example is shown in Listings 6-14 and 6-15.)


Figure 6-9: ObjectList item commands appear below the details page on a Pocket PC but on an intermediate page (after the user selects an item) on the Nokia June 2000 simulator.

You can specify item commands using the optional <Command> element. The following example displays a link with the text "Champions Cup" and sets the name associated with this command to "ChampsCup." (You can access this value in your event handler method.)

<Command Name="ChampsCup" Text="Champions Cup"/>

You must specify the event handler method to call in the ItemCommand property. In the event handler, you can determine which command item the user selects by getting the CommandName property of the ObjectListCommandEventArgs argument.

When you define item commands using the <Command> element, the runtime builds ObjectListCommand objects and places them in an ObjectListCommandsCollection object. You can access this collection through the Commands property of the ObjectList class in code and add, remove, or modify the item command objects it contains. For more details on working with this collection, see the section "Providing Different Commands for Different List Items," later in this chapter.

Listings 6-14 and 6-15 improve on the previous example. In Listing 6-15, the TeamStats class that defines our data source records now has two additional fields, ChampionsCup and InterCup, which record the success of a team in two fictional knock-out cup competitions. In the <Field> definitions in ObjectListItemCommandsExample.aspx (Listing 6-14), the application loads these two new fields into the control. However, we've set the Visible property to False, so these fields don't appear on the main page.

On Pocket Internet Explorer, selecting a team from the initial list will lead a user to the team's page. This screen now contains two new commands, in addition to the standard Back button. When the user selects either the Champions Cup or the Inter-City Cup command, the code calls the Team_OnItemCommand event handler. There the code tests the CommandName property to determine which option the user chose. The code also sets the label on the form Form2 with the result for the requested competition (retrieved from the ObjectListItem object passed in the parameter) or the string Did not compete if the source property is null.

Listing 6-14: Source for ObjectListItemCommandsExample.aspx






<%@ Page Inherits="MSPress.MobWeb.ObjListCmdsEx.MyWebForm" Language="c#"
CodeBehind="ObjectListItemCommandsExample.aspx.cs"
AutoEventWireup="False" %>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<mobile:Form runat="server" id="Form1">
<mobile:Label runat="server" StyleReference="title">
Season 2003 results</mobile:Label>
<mobile:ObjectList id="ObjectList1" runat="server"
AutoGenerateFields="false"
LabelField="TeamName">
<Field Title="Team" DataField="TeamName"></Field>
<Field Title="Won" DataField="Won"></Field>
<Field Title="Drawn" DataField="Drawn"></Field>
<Field Title="Lost" DataField="Lost"></Field>
<Field Title="Points" DataField="Points"></Field>
<Field Title="Champs. Cup" DataField="ChampionsCup"
Visible="false">
</Field>
<Field Title="Inter-City Cup" DataField="InterCup" Visible="false">
</Field>
<Command Name="ChampsCup" Text="Champions Cup"/>
<Command Name="InterCityCup" Text="Inter-City Cup"/>
</mobile:ObjectList>
</mobile:Form>
<mobile:Form runat="server" id="Form2">
<mobile:Label runat="server" StyleReference="title">
Season 2003 European Results</mobile:Label>
<mobile:Label runat="server" id="Label1"/>
<mobile:Link runat="server" NavigateUrl="#Form1">
Back
</mobile:Link>
</mobile:Form>












Listing 6-15: Code-behind file ObjectListItemCommandsExample.aspx.cs






using System;
using System.Collections;
using System.Web.UI.MobileControls;
namespace MSPress.MobWeb.ObjListCmdsEx
{
public class MyWebForm : System.Web.UI.MobileControls.MobilePage
{
protected ObjectList ObjectList1;
protected Form Form2;
protected Label Label1;
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
this.ObjectList1.ItemCommand +=
new ObjectListCommandEventHandler(this.Team_OnItemCommand);
}
private void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
ArrayList array = new ArrayList();
array.Add(new TeamStats("Dunes",1,38,24,8,6,80,
"Quarter Finals","));
array.Add(new TeamStats("Phoenix",2,38,20,10,8,70,
"Quarter Finals","));
array.Add(new TeamStats("Eagles",3,38,20,9,9,69,
","Winners"));
array.Add(new TeamStats("Zodiac",4,38,20,8,10,68,
"Semi Finals","));
ObjectList1.DataSource = array;
ObjectList1.LabelField = "TeamName";
ObjectList1.DataBind();
}
}
private void Team_OnItemCommand(
Object sender,
ObjectListCommandEventArgs e)
{
Label1.Text = "Did Not Compete"; //Default
this.ActiveForm = Form2;
if (e.CommandName == "ChampsCup")
{
// Set the label to the Champions Cup result.
if (e.ListItem["ChampionsCup"] != ")
Label1.Text = "Champions Cup: " +
e.ListItem["ChampionsCup"];
}
else if (e.CommandName == "InterCityCup")
{
// Set the label to the Inter-City Cup result.
if (e.ListItem["InterCup"] != ")
Label1.Text = " Inter-City Cup: " +
e.ListItem["InterCup"];
}
}
}
class TeamStats
{
private String _teamName;
private int _position, _played, _won, _drawn, _lost, _points;
private String _champsCup, _interCup;
public TeamStats(String teamName,
int position,
int played,
int won,
int drawn,
int lost,
int points,
String championsCup,
String interCup)
{
this._teamName = teamName;
this._position = position;
this._played = played;
this._won = won;
this._drawn = drawn;
this._lost = lost;
this._points = points;
this._champsCup = championsCup;
this._interCup= interCup;
}
public String TeamName { get { return this._teamName; }}
public int Position { get { return this._position; }}
public int Played { get { return this._played; }}
public int Won { get { return this._won; }}
public int Drawn { get { return this._drawn; }}
public int Lost { get { return this._lost; }}
public int Points { get { return this._points; }}
public String ChampionsCup { get { return this._champsCup; }}
public String InterCup{ get { return this._interCup; }}
}
}












Providing Different Commands for Different List Items


By default, the <Command> element defines item commands that appear on the details page whichever item in the list the user selects. However, you can customize the item commands that are displayed so that when a user selects a particular item in the list, fewer item commands are displayed, or you can create additional item commands to display just for that data item.

You do this by specifying an event handler for the ShowItemCommands event. The ObjectList control raises this event before the item commands are displayed. A ShowItemCommands event handler takes an argument of type ObjectListShowCommandsEventArgs that has two properties:



CommandsThis is the same collection of commands that you might have specified using the <Command> element, which is of type ObjectListCommandsCollection. You can use the Add, AddAt, Remove, and RemoveAt methods to manipulate this collection. Any changes you make apply only to the current item and don't affect the available commands collection should the user make subsequent selections.



ListItemThis returns the item that the user selects.



Listings 6-16 and 6-17 improve on the previous example. When the displayed item already appears as the top list item, the application removes the Team Before command from the item commands collection. Likewise, when the bottom item is displayed, the code removes the Team Below command. The only changes from the previous example are the wiring up of the ShowItemCommands event handler in Listing 6-17 to the event handler (called SetItemCommands), which implements the logic just described. Now the "Champions Cup" and "Inter Cup" item commands are displayed only if the team entered the competition (and if the ChampionsCup or InterCup fields in the source data item are not null).

Listing 6-16: Source for ObjectListOnShowItemsExample.aspx






<%@ Page Inherits="MSPress.MobWeb.ObjListShowItems.MyWebForm" Language="c#"
CodeBehind="ObjectListOnShowItemsExample.aspx.cs"
AutoEventWireup="False" %>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<mobile:Form runat="server" id="Form1">
<mobile:Label runat="server" StyleReference="title">
Season 2003 results</mobile:Label>
<mobile:ObjectList id="ObjectList1" runat="server"
AutoGenerateFields="true"
LabelField="TeamName">
<Command Name="ChampsCup" Text="Champions Cup"/>
<Command Name="InterCityCup" Text="Inter-City Cup"/>
</mobile:ObjectList>
</mobile:Form>
<mobile:Form runat="server" id="Form2">
<mobile:Label runat="server" StyleReference="title" id="Label1"/>
<mobile:Label runat="server" id="Label2"/>
<mobile:Link runat="server" NavigateUrl="#Form1">
Back
</mobile:Link>
</mobile:Form>












Listing 6-17: Code-behind file ObjectListOnShowItemsExample.aspx.cs






using System;
using System.Collections;
using System.Web.UI.MobileControls;
namespace MSPress.MobWeb.ObjListShowItems
{
public class MyWebForm : System.Web.UI.MobileControls.MobilePage
{
protected ObjectList ObjectList1;
protected Form Form2;
protected Label Label1;
protected Label Label2;
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
this.ObjectList1.ItemCommand += new
ObjectListCommandEventHandler(this.Team_OnItemCommand);
this.ObjectList1.ShowItemCommands += new
ObjectListShowCommandsEventHandler(this.SetItemCommands);
}
private void Page_Load(Object sender, EventArgs e)
{
// Not shown
// As in previous example
}
private void Team_OnItemCommand(
Object sender,
ObjectListCommandEventArgs e)
{
this.ActiveForm = Form2;
if (e.CommandName == "ChampsCup")
{
// Set the label to the Champions Cup result.
Label1.Text = "Champions Cup 2003";
Label2.Text = e.ListItem["ChampionsCup"];
}
else if (e.CommandName == "InterCityCup")
{
// Set the label to the Inter-City Cup result.
Label1.Text = "Inter-City Cup 2003";
Label2.Text = e.ListItem["InterCup"];
}
}
private void SetItemCommands(
Object sender,
ObjectListShowCommandsEventArgs e)
{
// Remove either the Champions Cup or Inter-City Cup
// command if the team didn't compete (if field is blank).
if (e.ListItem["ChampionsCup"] == ")
e.Commands.Remove("ChampsCup");
if (e.ListItem["InterCup"] == ")
e.Commands.Remove("InterCityCup");
}
}
class TeamStats
{
private String _teamName;
private int _position, _played, _won, _drawn, _lost, _points;
private String _champsCup, _interCup;
public TeamStats(String teamName,
int position,
int played,
int won,
int drawn,
int lost,
int points,
String championsCup,
String interCup)
{
this._teamName = teamName;
this._position = position;
this._played = played;
this._won = won;
this._drawn = drawn;
this._lost = lost;
this._points = points;
this._champsCup = championsCup;
this._interCup= interCup;
}
public String TeamName { get { return this._teamName; }}
public int Position { get { return this._position; }}
public int Played { get { return this._played; }}
public int Won { get { return this._won; }}
public int Drawn { get { return this._drawn; }}
public int Lost { get { return this._lost; }}
public int Points { get { return this._points; }}
public String ChampionsCup { get { return this._champsCup; }}
public String InterCup{ get { return this._interCup; }}
}
}











Displaying a Single Field, with Multiple Fields as a Secondary Function


In this usage of the ObjectList control, the list is displayed the same way as it appears with a List control. Therefore, selecting an item from the list causes an event handler method to execute.

If you select more than one field to display from the data source, the control still renders a user interface that allows the user to view these fields, but this is no longer the list's primary purpose. A More link is displayed on the same line as the selection item (in HTML browsers), or a Details option is displayed on a subsidiary screen after the user makes the initial selection (in WML browsers). The extra fields can be viewed by users to give them additional information about the main list item to help them make the correct selection. Figure 6-10 shows both these scenarios.


Figure 6-10: In Pocket Internet Explorer, selecting an item from the list raises the ItemCommand event with a CommandName defined by the DefaultCommand property, which in this example displays another Form (the center image). The user can click the More link on the first screen to access the details display (right-hand image).

To enable this behavior, set the DefaultCommand property to a unique command name and the ItemCommand event to the name of an event handler routine. This is the same event handler that manages item commands, as described in the previous example. For the default command, the code makes a call to the ItemCommand event handler with the argument's CommandName property set to the name you define in the DefaultCommand property.

One word of caution: if you decide to use the DefaultCommand property, you must always repeat the default command as one of the item commands that you designate with the <Command> element. For example, this code segment offers the TeamPoints command both as the DefaultCommand property and as a <Command> item command:

<mobile:ObjectList id="oblTeamList" runat="server" 
OnItemCommand="Team_OnItemCommand"
DefaultCommand="TeamPoints"
LabelField="TeamName">
<Command Name="TeamPoints" Text="Points"/>
<Command Name="TeamAbove" Text="Team Above"/>
<Command Name="TeamBelow" Text="Team Below"/>
</mobile:ObjectList>

On HTML browsers, the list item (in this example, TeamName) is rendered as a link that, when invoked, raises the ItemCommand event for the DefaultCommand property. Furthermore, a More link on the same line grants access to the other fields, as Figure 6-10 shows. On a small WML browser, the list item isn't rendered in this way. Instead, when the user selects a list item, the control displays a second screen containing only the item commands. If you don't duplicate the DefaultCommand option in your <Command> item commands, the user of a WML browser never sees a link to your DefaultCommand option.

Another word of caution: On an HTML browser, selecting an item from the list invokes the DefaultCommand action, which may well display a new Form control. But as Figure 6-10 shows, the item commands are displayed only on the details page (the right-hand image in Figure 6-10), but not on the page that displays when the user selects an item in the list (which is a Form you design yourself and not built-in functionality of the ObjectList control, an example of which is shown in the center image in Figure 6-10). By default, the user doesn't get to see the item commands unless he or she clicks the More link (now only a secondary function of the ObjectList control) to get to the details page. If the item commands provide functionality that is crucial to your application and you need to ensure that that functionality is available to your users after they select an item in the list, you must put standard mobile Command controls onto the form the user sees after they select an item. Program the Command controls to implement the same functionality as the item commands you defined in the ObjectList.

/ 145