7.8. Web State Management

A Web Forms page is re-created from scratch with each server round-trip. Information associated with the page's view states is saved automatically and restored during the page's load phase. This includes the state of the page and its current properties, as well as the state and base properties of the controls of the page. For example, the Text properties of controls, the Checked property of boxes and radio buttons, the Items object associated with a data list, and so on, are maintained across round-trips without our having to do anything. Values not associated with controls, however, are lost between round-trips, unless we explicitly preserve them. Let's look at an example that both illustrates Web state management and introduces us to a handful of additional controls.

The application is simple. We present the user with an ImageButton control that displays two figures: my daughter Anna and Winnie-the-Pooh. The user is asked to click on the button. If the user clicks on Winnie's face, it's considered a Pooh hit. If the user clicks on Anna's face, it's considered an Anna hit. Otherwise, it is considered a miss. The hit count is updated with each user click. In addition, we populate a ListBox control with the x/y coordinates of each user click, together with whether it is an Anna or a Pooh hit, or represents a miss.

In addition, we request that the user enter his or her name in a TextBox. We display the name in a Label object, then turn to false the Visible property of both the TextBox and the Label requesting the user name. A snapshot of the application is presented in Figure 7.4.

Figure 7.4. Session 2 of HitOrMissPooh


What's hard about this? Recall that each click represents a round-trip. The page and control properties, together with the data placed in the ListBox, TextBox, and Label objects, are saved and restored automatically in the page and control view states. The three hit count values, however, represent data that we have to manage ourselves.

The four instances recorded in the ListBox object represent the four clicks of the current session. The count below the picture records six hits, however. Although we see that two misses occurred, the miss count shows only one. The reason is that our representation doesn't persist across round-trips. The Pooh count lists four hits, but there was only one this session. The other three occurred in an earlier session. Our representation of this value persists not only across round-trips, but across page sessions as well. This is a bit too robust! The Anna count is the only correct hit count. In addition, the hit count across sessions is correctly persisted.

In the following sections we'll look at each of the state management solutions in turn. First let's briefly look at the TextBox, ImageButton, and ListBox controls.

7.8.1. Adding a TextBox Control

The TextBox control should be familiar from our use of it under Windows Forms. We can set the TextMode property to SingleLine, MultiLine, or Password. SingleLine accepts as many characters as specified by MaxLength or ends when the user hits Enter. Setting MaxLength to 0 allows an unlimited number of characters.

MultiLine causes one or two scroll bars to be inserted within the TextBox, which can now accept an unlimited number of text lines. If the Wrap property is set to true, a new line is generated whenever the text extends past the length of the TextBox. Only a single north-south scroll bar is present. If the Wrap property is set to false, each line extends until the user enters a new line. A second east-west scroll bar is added. Password causes the entry to be displayed as asterisks.

The TextBox event handler in the example sets the Text property of a Label to a greet-the-user string. It then sets to false the Visible property of both the Label requesting the user's name and the TextBox holding the user's response, essentially wiping them from the display at the same time the greeting appears:

private void TextBox1_TextChanged(object sender, EventArgs e)
{
    Label1.Text = "Hello, " + TextBox1.Text;

    TextBox1.Visible = false;
    Label3.Visible = false;
}

7.8.2. Adding an ImageButton Control

What makes the ImageButton control interesting is that the event argument passed to the event handler contains the X and Y coordinate properties of the mouse click. This is how I determine the hit or miss characteristic of the click:

private void ImageButton1_Click( object sender,
                          System.Web.UI.ImageClickEventArgs e)
{
    // x and y hot zones for the image
    int [] AnnaZone = { 302, 388, 75, 194 };
    int [] PoohZone = { 62, 196, 108, 301 };

    // OK: simple test of hit or miss ...
    if ( e.X >= AnnaZone[0] && e.X <= AnnaZone[1] &&
         e.Y >= AnnaZone[2] && e.Y <= AnnaZone[3] )
    { ... }
    else
    if ( e.X >= PoohZone[0] && e.X <= PoohZone[1] &&
         e.Y >= PoohZone[2] && e.Y <= PoohZone[3] )
    { ... }
    else { ... } // miss ...
}

The ImageUrl property specifies the image to display. It can be either local or remote. The ToolTip property is useful because there is no Text property to provide instruction to the user. The ability to determine the mouse click location allows us to support different behaviors within the same button.

7.8.3. Adding a ListBox Control

The ListBox control in this example is being used only to display each mouse click. It does not support user selection of an item, so I have not associated an event handler with it. The code to add an item to the ListBox looks like this:

private void
ImageButton1_Click( object sender,
                       System.Web.UI.ImageClickEventArgs e)
{
    string coords =
           e.X.ToString() + ":" + e.Y.ToString();
           
    if ( e.X >= AnnaZone[0] && e.X <= AnnaZone[1] &&
         e.Y >= AnnaZone[2] && e.Y <= AnnaZone[3] )
    {
         coords += " : Anna";
         // ...
    }

    // same for Pooh and for a miss ...

    ListBox1.Items.Add( coords );
}

Items is the collection object in which the elements are stored. It is a specialized class named ListItemCollection. It supports both Capacity and Count properties, and provides an indexer for element access, as well as methods for adding, searching, and removing elements.

The ListBox can have its SelectionMode property set for either Single or Multiple selection. Under Single selection, SelectedIndex holds the index of the selected item, or –1 to indicate that no selection has been made. Under Multiple selection, SelectedIndex holds the index of the lowest item selected. To find the remaining items selected, we iterate across each item, testing its Selected property. SelectedItem holds a reference either to the selected item in Single mode, or to the lowest indexed selected item in Multiple mode. For example, here is an event handler for ListBox selection events that handles both Single and Multiple modes:

private void
ListBox1_SelectedIndexChanged( object sender, EventArgs e)
{
    int ix = ListBox1.SelectedIndex;

    if ( ix == -1 ) // shouldn't happen
         return;
    if ( ListBox1.SelectionMode == ListSelectionMode.Single )
    {
         // OK: one item; let's get it and do something ...
         ListItem li = ListBox1.SelectedItem;

         // the something goes here ...
         return;
    }

    // maximum required capacity
    ArrayList select_elems = new ArrayList(ListBox1.Items.Count);
    select_elems.Add( ListBox1.Items[ ix++ ] );

    // this could also have been
    // select_elems.Add( ListBox1.SelectedItem );

    // now we need to collect the other selections ...
    while ( ix < ListBox1.Items.Count )
            if ( ListBox1.Items[ ix ].Selected )
                 select_elems.Add( ListBox1.Items[ ix++ ] );
            else break;

    // OK: now we do something with them
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.71.28