Adding Conditional Statements to the Sample Program


It's time to add code to our sample application. In this section you will add the conditional statements. Before adding the code however, a little explanation of what the application does is in order. You are writing a scaled-down version of a shopping cart. Here's how it works. You select an item to purchase from a list of items, then specify the quantity, and click the add button. As you add items, a table in the middle of the page displays the items purchased, their description, and their unit price ( Figure 3.26 ). Before you purchase any items, the page displays that the shopping cart is empty ( Figure 3.27 ). When you are done purchasing items, click the Place Order button. Clicking the button sends you to another page where you get a thank-you message and the total for the order ( Figure 3.28 ).

Figure 3.26. Beautiful isn't it? It is the sample application with a few items added to the shopping cart.

graphics/03fig26.gif

Figure 3.27. When the cart is empty, the application hides the grid and displays a label instead.

graphics/03fig27.gif

Figure 3.28. When the user clicks Place Order, the application jumps to another page that displays the total for the order and a thank-you message.

graphics/03fig28.gif

To complete this program you're going to have to use one of the ASP.NET intrinsic objectsthe Session object. I explained the Session object briefly in Chapter 2, "C# Building Blocks." The Session object works like a filing cabinet. It is similar to the Application object you used in Chapter 2 except that rather than storing information for all users, the Session object can store different information per user. You use it by adding objects to the Session object and associating each object with a key. It's easy to add objects to the Session object; all you have to do is enter a line like the following:

 Person p1 = new Person(); Session["Jose"] = p1; 

The above lines add the Person object in p1 to the Session object and assign the key "Jose" to the object. The information added to the Session object is only for the user accessing the page at the moment. If other users access the page, they may have something totally different in their Session object. To retrieve the information from the Session object you just reverse the process, like this:

 Person p1 = (Person) Session["Jose"]; 

In this case Session returns something of type object. In order to assign the result to the Person variable we need to convert the result to a Person . The conversion only works if the thing we put into "Jose" was a Person to begin with. But the C# language requires you to be very explicit about conversions. What if there is no item in Session with the key "Jose" ? Then, Session ["Jose"] will return null .

In addition to the Session object, you are going to use another class called the ArrayList . The ArrayList is a class that can maintain a dynamic array of items. Its complete name (as written by Microsoft) is System.Collections.ArrayList . It's kind of like the HashTable that you used in Chapter 2, except that you don't assign a key to each item. It is just a place to store objects, and then navigate through them one by one. We are going to use the ArrayList to store the purchased items. Then we are going to put the ArrayList object into the Session object so that every user will have his own ArrayList (i.e. set of purchased items). When the user clicks on the Place Order link we are going to retrieve the ArrayList from Session and add the price times the quantity for the items in the ArrayList .

I hope this doesn't sound too complicated. Let's get to it.

To add conditional statements to the sample application:

  1. First let's add the definition for the PurchasedItem class. The PurchasedItem class will be used to store each item that the customer purchases. Right-click on the file enterorder.aspx in Solution Explorer and choose View Code from the menu.

  2. Locate the lines that read:

     namespace loopsandconditionals  { 

    After that line, add the code in Figure 3.29 .

    Figure 3.29 The PurchasedItem class keeps information about a purchased item. When the user clicks the Add button to add the item to the shopping cart, the application creates an instance of this class to keep track of the item.
     class PurchasedItem {    string name;    int qty;    public void SetInfo(string name, int qty)    {       this.name = name       this.qty = qty    }    public string Name    {       get       {          return name;       }    }    public int Quantity    {       get       {          return qty;       }    } } 
  3. Now add a variable to your WebForm1 class of type ArrayList . Type ArrayList items; after the declaration for the fields that store the Web Controls ( Figure 3.30 ).

    Figure 3.30 The ArrayList is a class that Microsoft provides to store a collection of objects. The objects can be of any type. The list grows automatically as you add objects to it.
     using System.Web.UI; public class WebForm1 : System.Web.UI.Page {   protected WebControls.Button   btnAdd;   protected WebControls.Label   lblItem;   protected WebControls.TextBox   txtQty;   protected WebControls.Label   lblQty;   protected WebControls.DataGrid   grdItems;   protected WebControls.DropDownList   lstItems;   protected WebControls.Label   lblEmpty; protected WebControls.HyperLink   lnkOrder;  ArrayList items;  
  4. After the declaration line in step 3, it would be handy to define a few support functions. In particular, one function to show the grid and one to hide the grid, depending on whether there are items on the list or not. These functions are called ShowGrid and HideGrid ( Figure 3.31 ).

    Figure 3.31 The ShowGrid function does what its name implies, shows the grid and hides the label that says that the cart is empty. The HideGrid function does the opposite .
     private void ShowGrid() {    lblEmpty.Visible = false;    grdItems.Visible = true; } private void HideGrid() {    lblEmpty.Visible = true;    grdItems.Visible = false; } 
  5. One more support function is needed, one to bind the grid to the array list. This code uses the grid's databinding feature. Databinding is a handy feature. You set the DataSource property of the grid to a list object, like the ArrayList . The grid takes care of navigating through the items in the list and updating its data to match the elements. Each column in the grid has a DataField property. The grid reads each object from the list and looks for a property in the object named the same as the DataField . So, all we have to do is make sure our class PurchasedItem has properties, and that we set the columns ' DataFields to the names of the properties. The grid control will take care of displaying the data properly. Add the code in Figure 3.32 after the HideGrid function.

    Figure 3.32 UpdateGrid binds the data grid to the array list. The grid control automatically updates itself to show the items in the array list. There will be one row for each purchased item. The columns of the grid will be bound to properties in each object.
     private void UpdateGrid() {    grdItems.DataSource = items;    grdItems.DataBind(); } 
  6. In Solution Explorer, right-click on enterorder.aspx and choose View Designer from the context menu.

  7. Double-click on an empty space on the form. This will make the code editor add a Page_Load function if it has not already been added.

  8. In Page_Load , add the code in Figure 3.33 . This code does two things. First it checks if Session already contains the ArrayList object. If it doesn't, we create the ArrayList object and add it to Session . The second part of the code checks if we have items in the ArrayList . If we don't have items, then we hide the grid (i.e. call HideGrid ). If we do have items then we show the grid (i.e. call ShowGrid ).

    Figure 3.33 Every time the client requests a Web form, ASP.NET calls the Page_Load function in your code. In this form we see if there is a list of items already present in Session. If not we create a new array list and save it in Session. If the list (previously there or newly created) contains no items, then we hide the grid and show the label that says the cart is empty. If there are items, we show the grid and hide the label.
     private void Page_Load(object sender, System.EventArgs e) {  if (Session["items"] == null)   {   items = new ArrayList();   Session["items"] = items;   }   else   items = (ArrayList)Session["items"];   if (items.Count == 0)   HideGrid();   else   {   ShowGrid();   UpdateGrid();   }  } 
  9. In Solution Explorer right-click on enterorder.aspx and choose View Designer from the context menu.

  10. Double-click on the Add button. This will make the code editor add a btnAdd_Click function if it has not already been added.

  11. Add the code in Figure 3.34 inside the btnAdd_Click function. This code reads the contents of the fields (item selected and quantity) and if they are valid creates a PurchasedItem object with the information and adds it to the ArrayList .

    Figure 3.34 When the user clicks the Add button, the code reads the contents of the item and qty fields. Notice that it needs to convert the qty text field into a numeric value. Then if the fields aren't empty, the code creates a new PurchasedItem, sets the information in the object, and adds it to the ArrayList.
     private void btnAdd_Click(object sender,                     System.EventArgs e) {  int qty = 0;   if (txtQty.Text != null)   qty = System.Convert.ToInt32   (txtQty.Text);   string name = lstItems.SelectedItem.   Value;   if (qty >= 0 && name != "")   {   PurchasedItem pi =   new PurchasedItem();   pi.SetInfo(name,qty);   items.Add(pi);   ShowGrid();   UpdateGrid();   }  } 
  12. Finally, let's enhance the PurchasedItem class. The PurchasedItem class needs to have two properties: Description and Price . Of these, Description gives the description for the item. It is a property that returns a different string using a switch statement depending on the item that PurchasedItem is storing. Price works in the same fashion. It reports a price for the current item based on a switch statement. Add the highlighted code in Figure 3.35 ( next page) to your project inside the PurchasedItem class.

    Figure 3.35 The Description and Price fields are calculated based on the name of the item.
     class PurchasedItem {    string name;    int qty;    public void SetInfo(string name,                       int qty)    { ... }    public string Name { ... }    public int Quantity { ... }  public string Description   {   get   {   string desc="";   switch(name)   {   case "Notebook":   desc = "A small computer";   break;   case "Desktop":   desc = "A big computer";   break;   case "FlatMon":   desc =   "A sweet looking monitor";   break;   case "FatMon":   desc = "An old fat monitor";   break;   default:   desc = "unknown item";   break;   }   return desc;   }   }   public double Price   {   get   {   double price = 0.0;   switch(name)   {   case "Notebook":   price = 1999.99;   break;   case "Desktop":   price = 899.00;   break;   case "FlatMon":   price = 1500.00;   break;   case "FatMon":   price = 300.00;   break;   default:   price = 0.0;   break;   }   return price;   }   }  } 

graphics/tick.gif Tip

  • At this point your application should compile and run. The only code missing is the code that displays the total when the Place Order link is clicked.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

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