Step by Step: Implement Style List Controls by Using the .NET Compact Framework on Smartphone

 

Microsoft Corporation

February 2005

Applies to:
   Microsoft Visual Studio .NET 2003
   Microsoft .NET Compact Framework version 1.0*
   ASP.NET version 1.1
   Windows Mobile-based Smartphones
   Microsoft Windows

*If your machine is using .NET Compact Framework version 1.0 SP2, please see Appendix A.

Summary: The objective of this exercise is to create an owner-drawn ListView representing the top 10 high scores in the same style as native Smartphone applications. The data will be retrieved from a Web service in the form of a DataSet. This exercise builds on the previous exercise Step by Step: Implement Smartphone-Style Scrolling Data Entry Dialogs by Using the .NET Compact Framework on Smartphone. This exercise will take approximately 25 minutes to complete. (15 printed pages)

Download Lab 3 Implementing SP 2003 Style List Controls.msi from the Microsoft Download Center.

Contents

Part 1: Creating a New Form for the ListView
Part 2: Implementing the Owner-Drawn ListView
Part 3: Consuming the Web Service and Adding Data to the ListView
Appendix A: Using .NET Compact Framework Version 1.0 SP2

To complete this exercise, you will need:

  • Smartphone 2003 SDK
  • Smartphone 2003 emulator
  • Smartphone 2003 SE QVGA (Virtual Radio) – SDK emulator
  • Internet connection

Note For this exercise to work, your computer cannot be RASed in to the Microsoft network. Also, this exercise will not work if you are using a virtual computer.

This exercise builds on the previous exercise Step by Step: Implement Smartphone-Style Scrolling Data Entry Dialogs by Using the .NET Compact Framework on Smartphone.

Part 1: Creating a New Form for the ListView

In this part of the exercise, you will perform the following tasks:

  • Create the Smartphone client
  • Create the Smartphone menu

Some illustrations in this part of the exercise are thumbnails. You can click the thumbnails for larger images.

Creating the Smartphone Client

In this task, you will create the Smartphone client.

To create the Smartphone client

  1. Create a folder on drive C, and then rename this folder Labs.

  2. Copy the Smartphone2003 folder from the download, and then paste it into the C:\Labs folder.

  3. Start Microsoft Visual Studio .NET 2003.

  4. On the File menu, point to New, and then click Project.

  5. In the Project Types list, select Visual C# Projects.

  6. Under Templates, select Smart Device Application, as shown in the following illustration.

    Click here for larger image

  7. In the Name box, delete the existing text and type HighScores.

  8. In the Location box, delete the existing text and type C:\Labs\Smartphone2003\Lab3.

    Important Be sure that file names and locations are correct throughout the exercise. If not, the exercise may not work.

  9. Click OK to launch the Smart Device Application Wizard.

  10. Select the Smartphone platform and Windows Application project type, and then click OK, as shown in the following illustration.

    Click here for larger image

    These actions create a basic application with a form and empty menu.

Creating the Smartphone Menu

Now you will add the menu structure for the application. A traditional Microsoft Windows or Pocket PC application can have multiple top-level and nested menus. The Smartphone user interface has been simplified to include two top-level menu items, which map to hardware keys below the screen. These top-level menus are called softkeys. If the softkey does not have a pop-up menu, pressing the softkey will run the top-level menu item. If the softkey does have submenu items, pressing the softkey will open the submenu. The user can then use the directional keypad to navigate and choose the menu item.

Note If you create a Microsoft .NET Compact Framework Smartphone application with a pop-up menu for the left softkey, the application will compile; however, the runtime will throw a not-supported exception at run time.

To add the menu structure for the application

  1. In Visual Studio .NET 2003, in the lower-left corner of the Designer view, click the mainMenu1 control.

    This will extend the form to include the menu. It is now ready for editing, as shown in the following illustration.

  2. Click Type Here, and then type Get Scores, as shown in the following illustration.

    This step will create the left softkey menu item. A placeholder has been created for a new menu item to the right of the left menu item.

  3. Click the rightmost Type Here, and then type Done, as shown in the following illustration.

    The menu structure is now complete, but it does not respond to user input. You need to raise events when the user chooses a menu item.

  4. Double-click the Get Scores menu item to create a new click handler. This step switches the view to Code view to show the code behind the form and adds the following method signature:

  5. Press SHIFT+F7 to switch the view back to form design view.

  6. Double-click the Done menu item to create a new click handler.

  7. Within this method, add the following code to close the form.

    Application.Exit();
    
  8. Press SHIFT+F7 to switch the view back to form design view.

  9. Select the form, and then change the Text property from Form1 to High Scores.

Part 2: Implementing the Owner-Drawn ListView

In this part of the exercise, you will extend a custom class to provide owner-drawn functionality for a ListView-style control.

To extend a custom class

  1. On the File menu, click Add Existing Item.

  2. Check that the current directory is C:\Labs\Smartphone2003\Lab3\Code. If it is not, browse to this directory, as shown in the following illustration.

  3. Select the ListView.cs file, and then click Open to add the file to the project. This will copy the file into your project directory.

  4. Double click ListView.cs in the Solution Explorer to open the file.

    This file provides the ability to create an owner-drawn ListView; only the base functionality is complete, however. The contents for this file are as follows:

    • The first class is ScoreItem. This class is designed to hold a bold title line and a detail line for each ListView item. For this exercise example, the constructor accepts a DataRow and then constructs the title and detail members; this class, however, can hold a variable number of lines.
    • The last class in the file is OwnerDrawnList. This class provides the base functionality required for an owner-drawn ListView. It uses a scroll bar to provide scrolling, a bitmap on which to draw the ListView items, and an ArrayList to store the items to draw.

    The class of greatest interest for the sake of this exercise in is ListViewSP. This class inherits from OwnerDrawnList but provides its own OnPaint method.

  5. Locate the following comment in the ListViewSP.OnPaint method.

    // TODO: Set background color  
    
  6. After the comment, add the following code to set the background color for the client view.

    gOffScreen.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle);
    

    The method then parses each visible item for drawing.

  7. Locate the comment.

    //TODO: Get the listview item data and draw the listview item
    
  8. After the comment, add the following code.

    //Get a ScoreItem object from the ArrayList Items.
    ScoreItem lvi = (ScoreItem)this.Items[n];
    
    //Get a normal and bold font
    Font boldFont = new Font(this.Font.Name, 10, FontStyle.Bold);
    Font font = new Font(this.Font.Name, 10, FontStyle.Regular);
    
    // Draw the row
    gOffScreen.DrawString(lvi.title, boldFont, new SolidBrush(fontColor), Column1Left, itemTop);
    gOffScreen.DrawString(lvi.delegateId, font, new SolidBrush(fontColor), Column2Left, itemTop);
    gOffScreen.DrawString(lvi.detail, font, new SolidBrush(fontColor), Column1Left, itemTop + (ItemHeight/2));
    gOffScreen.DrawString(lvi.date, font, new SolidBrush(fontColor), Column2Left, itemTop + (ItemHeight/2));
    
    // Cleanup the fonts
    boldFont.Dispose();
    font.Dispose();
    

Part 3: Consuming the Web Service and Adding Data to the ListView

In this part of the exercise, you will perform the following tasks:

  • Consume a Web service retrieving a DataSet object
  • Add data to the ListView

Consuming the Web Service

In this task, you will consume a Web service in the form of a DataSet.

To add the Web reference

  1. On the Project menu, click Add Web Reference, as shown in the following illustration.

    Click here for larger image

  2. In the Add Web Reference dialog box, in the URL text box, type https://mobile.msdevtools.net/SnakeScores2/default.asmx, and then click Go.

  3. In the Web reference name box, type ScoreService, as shown in the following illustration.

    Click here for larger image

  4. Click Add Reference. Visual Studio .NET will now generate the relevant proxy class to invoke the Web service.

Adding Data to the Listview

In this task, you will add data to the Listview, fix the Quarter Video Graphics Array (QVGA) issue, and test the application.

To invoke the Web service and extract the data

  1. In the Solution Explorer, double-click Form1.cs to open the High Scores form.

  2. Press F7 to switch the view to Code view. Because you have not created a design-time version of the ListViewSP class, you cannot add it to the Toolbox. Therefore, you will add a reference to the class programmatically.

  3. Locate the following variable declaration in the HighScores class.

    private System.Windows.Forms.MainMenu mainMenu1;
    
  4. After this declaration, add a definition for your ListViewSP class.

    ListViewSP listViewScores;
    
  5. Locate the following comment in the HighScores constructor.

    //
    // TODO: Add any constructor code after InitializeComponent call
    //
    
  6. After the comment, add the following code to set up your ListViewSP class.

    listViewScores = new ListViewSP();
    listViewScores.Parent = this;
    
    // Set the bounds of the listview.
    listViewScores.Bounds = this. ClientRectangle;
    // Get the listview to initialize and set column sizes / row heights
    listViewScores. Initialize();
    

    Finally ,you want to invoke the Web service when the left softkey is selected.

  7. Locate the following event handler for the left softkey.

    private void menuItem1_Click(object sender, System.EventArgs e) {
    
  8. Add the following code to the handler.

    // Set wait cursor
    Cursor.Current = Cursors.WaitCursor;
    // Create WS proxy
    ScoreService.Scores service = new ScoreService.Scores();
    // Get scores
    try {
        System.Data.DataSet dsScores = service.GetScores();
    
        listViewScores.Items.Clear();
    
        // Add items to listview
        foreach(System.Data.DataRow dr in dsScores.Tables[0].Rows) {
            listViewScores.Items.Add(new ScoreItem(dr) );
        }
    
        // Set the bounds of the listview
        listViewScores.Bounds = new Rectangle(0,0, this.ClientSize.Width, this.ClientSize.Height);
    
        // Select the first item
        listViewScores.SelectedIndex = 0;
        listViewScores.EnsureVisible(listViewScores.SelectedIndex);
        listViewScores.Refresh();
    }
    
    catch (Exception ex) {
        // Display error and close form
        Cursor.Current = Cursors.Default;
        MessageBox.Show(ex.Message, "Web service error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
    }
    
    finally {
        // Reset cursor
        Cursor.Current = Cursors.Default;
    }
    

    You can now test the Listview functionality.

  9. To test the application, press F5.

    Visual Studio .NET will present the options for deploying the application, as shown in the following illustration.

  10. Select Smartphone 2003 Emulator (Virtual Radio) or WWE SP 2003 SE QVGA (Virtual Radio) - SDK Emulator, and then click Deploy.

    When Visual Studio .NET deploys the application to the emulator (or device), it will determine if the string resources for the System namespace are installed. If the emulator has been started from a cold boot, it will automatically copy a cabinet (.cab) file to the device and install the resources.

    If you see the following screen on your emulator, press the left softkey or press F1 to continue deploying your application.

  11. In the Smartphone 2003 emulator, wait for the application to load.

  12. Press the left softkey or press F1 to retrieve the high scores.

  13. Check that ListView is working correctly by scrolling up and down. If you are running the standard emulator, your screen should look like the following illustration:

    Note If you are not running the QVGA emulator, the display will not be formatted correctly, as shown in the following illustration. The reason is that the column and item height has been calculated with regard to the QVGA screen size.

  14. Use the softkeys to quit the client and end debugging.

To fix the QVCA issue

  1. Open the ListView.cs file.

  2. Locate the following lines.

    // TODO: Fix columns and item height for QVGA            
    Graphics g = this.CreateGraphics();
    Font font = new Font(this.Font.Name, 10, FontStyle.Bold);
    // Calc line height to be height of letter A plus 10%
    int fontHeight = (int)(g.MeasureString("A", font).Height*1.1);
    this.ItemHeight = fontHeight*2;
    g.Dispose();
    
    Column1Left = 5;
    Column2Left = 25;            
    
  3. Remove these lines in the Initialize method and replace with the following.

    Graphics g = this.CreateGraphics();
    Font font = new Font(this.Font.Name, 10, FontStyle.Bold);
    
    this.ItemHeight = this.Height /5;
    this.Column1Left = 5;
    this.Column2Left = (int)(g.MeasureString("Length 1000", font).Width);
    
    font.Dispose();
    g.Dispose();
    

    Note The code now sets the width of the second column depending on the width of a string, which will take into account different dots-per-inch (dpi) resolutions on the device; the height is based on five lines independent of resolution.

You can now test the code.

To test the application

  1. Press F5.

  2. Select Smartphone 2003 Emulator (Virtual Radio), and then click Deploy.

  3. Run the application again and make sure that the owner-drawn ListView is displayed correctly, as shown in the following illustration.

Congratulations! You have now completed this exercise.

Summary

In this exercise, you learned how to create a custom control that provided owner-drawn ListView functionality in accordance with the style of a native Smartphone application. A ListView can be used to present either a high-level list that summarizes data or an in-depth view of a particular entity.

One example of this functionality is the Contacts application.

This application provides a standard ListView to list all the contacts.
When the user selects a contact, it expands to an owner-drawn ListView, showing the detail for the contact. You could expand the ScoreItem class — which held the initials, length, delegate ID, and date — to hold other data, such as the height of the ListView item.
Finally, the user can edit the contact, showing the scrolling data entry dialog implemented in Smartphone Lab 2.

Figure 1. The contacts application providing owner-drawn listview functionality

Appendix A: Using .NET Compact Framework Version 1.0 SP2

If your computer has .NET Compact Framework version 1.0 SP2 installed and you have not updated the netcf.core.ppc3.ARM.cab and netcf.core.ppc3.x86.cab files in .NET Compact Framework version 1.0, you need to update these files prior to beginning this exercise. The installation of SP2 does not automatically update these .cab files for you.

To update the netcf.core.ppc3.ARM.cab and netcf.core.ppc3.x86.cab files in .NET Compact Framework version 1.0

  1. Open two instances of My Computer.
  2. In the first instance, browse to C:\Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000\Windows CE\wce300\arm.
  3. In the second instance, browse to C:\Program Files\Microsoft .NET Compact Framework 1.0 SP2.
  4. Copy the netcf.core.ppc3.ARM.cab file from the second instance and paste it into the first instance.
  5. Click Yes to replace the existing file.
  6. Change the location of first instance of My Computer to C:\Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000\Windows CE\wce300\x86.
  7. In the second instance, copy the netcf.core.ppc3.x86.cab file, and then paste it into the first instance.
  8. Click Yes to replace the existing file.