Wrox Home  
Search

Exercise Answers for Beginning ASP.NET 1.0 with C#.NET


Chapter Question
Number
Question Answer
4 1

What is a variable and how is it related to data types in C#?

A variable is a label or reference to a container in memory that is allocated a name by the programmer. The memory space allocated to a variable will remain empty until a value is associated with it, but the space it occupies will be reserved, regardless of the information that it may - or may not - contain.

Data types refer to the kind of data that is stored within a variable. There are many data types, such as int, string, char and so on. But they are all divided into two major types - value data types, and reference data types.

Use the books index, to refresh your memory about data types in detail, should you need to.

4 2

Use string, integer and date variables to create an ASPX file to display your name, age and date of birth.

<script language="c#" runat="server">
void Page_Load()
{
    string name = "Jake";
    int age = 40;
    DateTime dateOfBirth = Convert.ToDateTime("8/8/1962");

    Display1.Text = name;
    Display2.Text = age.ToString();
    Display3.Text = dateOfBirth.ToString();
}
</script>

<html>
<body>
    Hi, My name is
    <asp:label id="Display1" runat="server" />
    <br>I am
    <asp:label id="Display2" runat="server" />
    years old
    <br>I was born on
    <asp:label id="Display3" runat="server" />
</body>
</html>

4 3

Arrange the following into groups of numeric, character and miscellaneous data types, and give an example of a value and a use for each: int, char, byte, short, bool, string, long, float, double, decimalint, char, byte, short, bool, string, long, float, double, decimal

NUMERIC

CHARACTER

MISCELLANEOUS

Numeric Data TypesExample ValueUse
Integer467,892to store an integer within the range -2,147,483,648 to 2,147,483,647
Byte174to store an integer within the range 0 to 255
Short76to store an integer within the range -32,768 to 32,767
Long8,976,347,864to store an integer within the range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Single-1.6088E-10to store single precision floating-point numbers, within the range -3.402823E38 to -1.401298E-45 (for negative values), and 1.401298E-45 to 3.402823E38 (for positive values)
Double3.965468572385E-271to store double precision floating point numbers within the range -1.79769313486232E308 to -4.94065645841247E-324 (for negative values), and 4.94065645841247E-324 to 1.79769313486232E308 (for positive values)
Decimal12.76to store numbers with up to twenty-eight decimal places

Textual Data TypesExample ValueUse
String"I'm going to the shops"to store text
Char"A"Cto store letters as numbers, perhaps when making your own customized character sets

Miscellaneous Data TypesExample ValueUse
Date#09/09/1926# / #16:25:05#to store a date or time value
BooleanTrueto describe whether a particular condition is true or false
4 4

Write an ASPX file that will multiply the values of two integer variables together. Then modify the example to add, divide and subtract the two numbers.

<script language="C#" runat="server">
void Page_Load()
{
    int integer1;
    int integer2;
    int Total;
    integer1 = 10;
    integer2 = 5;
    Total = integer1 + integer2; //insert appropriate operator
    Display1.Text = Total.ToString();
}
</script>

<html>
<body>
    The result of your calculation is:
    <asp:label id="Display1" runat="server" />
</body>
</html>

4 5

Create an array containing your 5 favorite singers. Then concatenate the elements of your array into one string, and after the opening sentence "My 5 favorite singers are:", display them in a clear way using the <asp:label> control.

<script runat="Server" language="c#">
void Page_Load() {
    string [] strArraySinger= new string[5];
    strArraySinger[0] = "Aretha Franklin,";
    strArraySinger[1] = "Muddy Waters,";
    strArraySinger[2] = "the Sabri brothers,";
    strArraySinger[3] = "Frank Sinatra";
    strArraySinger[4] = "Elvis Presley.";

    singers.Text = strArraySinger[0] + " " + strArraySinger[1] + " " + strArraySinger[2] + " " + strArraySinger[3] + " and " + strArraySinger[4];
}
</script>

<html>
<body>
    My 5 favorite singers are:
    <br/>
    <asp:label id="singers" runat="server"/>
</body>
</html>



Chapter Question
Number
Question Answer
5 1

Explain why XML is so useful for storing data.

XML is useful for storing data for the following reasons:

  • It gives us a way to explicitly structure our data.
  • It lets us describe the meaning of our data as part of the structuring process.
  • It produces intuitive and easy-to-interpret documents.
5 2

Create an XML file to hold the following employee information:

Company: Wrox Press

employee: Hubert Welsch
employee number: 9862
contact numbers: ext - 346
        home - 8764 35733
length of service: 2 years
department: .NET Team

employee: Paul Crick
employee number: 7461
contact numbers: ext - 399
        home - 2138 90346
length of service: 8 months
department: .NET Team

employee: Alison Freyer
employee number: 7849
contact numbers: ext - 982
        home - 7893 42769
length of service: 4 years
department: Java Team

employee: Sandra Jackson
employee number: 9862
contact numbers: ext - 222
        home - 8974 389743
length of service: 1 year
department: Finance

<?xml version="1.0"?>

<company name="Wrox Press">
  <employee name="Hubert Welsch" number="9862">
    <contact_numbers>
      <office>ext.346</office>
      <home>8764 35733</home>
    </contact_numbers>
    <length_of_service>2 years</length_of_service>
    <department>.NET Team</department>
  </employee>
  
  <employee name="Paul Crick" number="7461">
    <contact_numbers>
      <office>ext.399</office>
      <home>2138 90346</home>
    </contact_numbers>
    <length_of_service>8 months</length_of_service>
    <department>.NET Team</department>
  </employee>
  
  <employee name="Alison Freyer" number="7849">
    <contact_numbers>
      <office>ext.982</office>
      <home>7893 42769</home>
    </contact_numbers>
    <length_of_service>4 years</length_of_service>
    <department>Java Team</department>
  </employee>
  
  <employee name="Sandra Jackson" number="9862">
    <contact_numbers>
      <office>ext.222</office>
      <home>8974 389743</home>
    </contact_numbers>
    <length_of_service>1 year</length_of_service>
    <department>Finance</department>
  </employee>
</company>

5 3

Create a cascading style sheet to display the XML file you have just created. Use font style and alignment, and color to display the employee information in an attractive way.

employee {
    display:block;
    background: #eeeecc;
    color: #7777bb;
    border-left:solid;
    border-top:solid;
    border-width:10;        
    padding:10,10,10,10
    }

name {
    display:block;
    font-family: Arial, Helvetica;
    font-weight: bold;
    font-size: 12pt;
    background: #ffffee;
    color: #aa0066;
    border-bottom:solid;
    border-top:solid;
    border-width:4;        
    }

number {
    display:inline;
    font-size: 8pt;
    font-weight: normal;
    color: #000000;
    }

contact_numbers {
    display:block;
    font-family: Verdana;
    font-size: 8pt;
    color: #336633;
    text-align: right;
    }

office {
    display:block;
    border-bottom:solid;
    border-width:1;        
    }

home {
    display:block;
    border-bottom:solid;
    border-width:1;        
    }

length_of_service {
    font-family: Arial, Helvetica;
    font-size: 12pt;
    color: black;
    }

department {
    font-family: Arial, Helvetica;
    font-size: 12pt;
    font-weight: bold;
    color: black;
    }

5 4

Are the following XML documents well-formed? If not, make the necessary corrections, and explain why your corrections are important in the creation of a well-formed document.

(a)

<?xml version="1.0"?>
<shoppingList>
  <title>Shopping List</title>
  <items>
    <fruit items>
      <item>Rasberries</item>
      <item>Apples</item>
      <item>Oranges</item>
    </fruit_items>
    <vegetable_items>
      <item>Carrots</item>
      <item>Onions</item>
      </vegetable_items>
    <other_items>
      <item>Floor cleaner</item>
      <item>Bread</item>
      <item>Toothpaste</item>
      <item>Pasta</item)
    </other_items>
  </items>
</shoppingList>
  <notes> Don't get cooking apples like last time and post letter to Harold</notes>

(b)

<?xml version="1.0">
<order>
  <salesperson>Sam Clarke</salesperson>
  <customer>Droutledge Waters</customer>
  <item>
    <description>snorkle</description>
    <quantity>37</quantity>
  </item>
  <date>
    <month>7</month>
    <day>6</day>
    <year>2001</year>
  </date>
</order>

Both of the XML documents are badly-formed.

a. The opening tag <fruit items> should be <fruit_items> so that it matches the element's closing tag </fruit_items>. An underscore is required to separate the two words, since spaces are not permissible as characters in XML element names.

The items element should be terminated with a closing tag </items>.

<?xml version="1.0"?>
<shoppingList>
  <title>Shopping List</title>
  <items>
    <fruit_items>
      <item>Rasberries</item>
      <item>Apples</item>
      <item>Oranges</item>
    </fruit_items>
    <vegetable_items>
      <item>Carrots</item>
      <item>Onions</item>
      </vegetable_items>
    <other_items>
      <item>Floor cleaner</item>
      <item>Bread</item>
      <item>Toothpaste</item>
      <item>Pasta</item>
    </other_items>
  </items>
  <notes> Don't get cooking apples like last time and post letter to Harold</notes>
</shoppingList>

b. The XML version directive requires a question mark before the closing > symbol

<?xml version="1.0"?>
<order>
  <salesperson>Sam Clarke</salesperson>
  <customer>Droutledge Waters</customer>
  <item>
    <description>snorkle</description>
    <quantity>37</quantity>
  </item>
  <date>
    <month>7</month>
    <day>6</day>
    <year>2001</year>
  </date>
</order>

5 5

Once you have finished looking at part b, try rearranging this information so you can view orders that have been placed via Sam Clarke the sales person. Add another order, placed the following week, for 12 goggles, as ordered by Aqua Lake Enterprises.

This information can be rearranged as follows so that it's possible to view orders placed via Sam Clarke the sales person. Here we have added another order, as described in the exercise:

<?xml version="1.0"?>
<salesperson name="Sam Clarke">
  <order>
    <customer>Droutledge Waters</customer>
    <item>
      <description>snorkle</description>
      <quantity>37</quantity>
    </item>
    <date>
      <month>7</month>
      <day>6</day>
      <year>2001</year>
    </date>
  </order>

  <order>
    <customer>Aqua Lake Enterprises</customer>
    <item>
      <description>goggles</description>
      <quantity>12</quantity>
    </item>
    <date>
      <month>7</month>
      <day>13</day>
      <year>2001</year>
    </date>
  </order>
</salesperson>



Chapter Question
Number
Question Answer
6 1

For each of the following Boolean expressions, say for what values of A each of them will evaluate to True and when they will evaluate to False.

a. NOT A > 0 OR A > 5

b. A > 1 AND A < 5 OR A > 7 AND A < 10

c. A < 10 OR A > 12 AND NOT A > 20

a.False if A is 0, 1, 2, 3, 4 or 5. True otherwise.

b.True if A is 2, 3, 4, 8 or 9. False otherwise.

c.True if A is 13, 14, 15, 16, 17, 18 or 19, or A is 9 or less. False otherwise.

6 2

Suggest a loop structure which would be appropriate for each of the following scenarios, and justify your choice:

a. Displaying a set of items from a shopping list, stored in an array

b. Displaying a calendar for the current month

c. Looking through an array to find the location of a specific entry

d. Drawing a chessboard using an HTML table

Bonus: write an ASP.NET page to perform one of these tasks.

a. For Each would be suitable, because it provides a simple way to handle every item in an array.
b. A For loop would be suitable, because we know how many days there are in the current month, so we can specify the number of times the loop needs to be performed before it starts.
c. Do ... While would probably work best, since it allows us to perform the loop until the entry has been found.
d. Tricky: you'd probably want to use two For ... Next loops, one inside the other. We need eight rows, each consisting of eight cells, so two loops, each of which take place eight times, would work fine.

6 3

Write a function that generates a random integer between two integers passed as parameters. Build an ASP.NET page which allows you to enter the lower and upper limits, and generates a set of random numbers in that range.

<%@ Page Language="c#" runat=server %>

<script runat=server>
void Page_Load()
{

if (Request.Form["num1"] != "" && Request.Form["num2"] != "")
{

int a = Convert.ToInt32(num1.Text);
int b = Convert.ToInt32(num2.Text);


int ans = RandomNumber(a, b);
answer.Text = ans.ToString();
}
}

int RandomNumber(int a, int b)
{
Random r = new Random();
int rnd = r.Next(10);
return ((b-a)*(rnd)/10 + a);
}


</script>

<html>
  <body>
    <form runat="server">
    Min: <asp:textbox id=num1  runat=server />
    Max: <asp:textbox id=num2  runat=server />
    <br />
    <input type="Submit" value="Pick random value between limits above">
    <br />
    <font size=16pt>Value: <asp:label id=answer runat=server /></font>

    </form>
  </body>
</html>

6 4

Suggest a situation when you might want to pass variables into a function by reference. Write an ASP.NET page to illustrate your example.

This is an open-ended question, so no solution is provided.



Chapter Question
Number
Question Answer
7 1

Explain why event-driven programming is such a good way of programming for the Web.

In an event-driven web page, code is not constrained to being executed in a predetermined order whenever the page is served. Rather, it can be broken up into dedicated blocks of functionality that will be executed in response to specific user-generated events. We can therefore piece together complex functionality from several independent components in a web form, and there is no need for the client software to know anything about how the components are programmed.

7 2

Run the following HTML code in your browser (remember to save the page with a .htm extension). Now translate the HTML into a set of ASP.NET server controls so that the information entered into the form is maintained when the submit button is clicked. Add a subroutine to the button to confirm that the details entered were received.

<html>
<head>
  <title>HTML</title>
</head>
<body>
  <form>
    <h4>Please enter your name:</h4>
    <input type="text"><br /><br />
    <h4>What would you like for breakfast?</h4>
    <h4>Cereal<input type="checkbox"></h4>
    <h4>Eggs<input type="checkbox"></h4>
    <h4>Pancakes<input type="checkbox"></h4>
    <h4>Feed me:</h4>
    <h4>Now<input type="radio"></h4>
    <h4>Later<input type="radio"></h4>
    <input type="submit" value="Thank you!">
  </form>
</body>
</html>

<%@ Page Language="C#" runat="server" %>

<script runat="server">
  void ClickHandler(object sender, EventArgs e)
{
message.Text = "Details received.";
    questions.Visible = false;
}
</script>

<html>
<head>
  <title>ASP.NET</title>
</head>
<body>

  <asp:label id=message runat=server />
  <form id=questions runat="server">

    <h4>Please enter your name:</h4>     <asp:textbox id=name runat="server" /><br /><br />

    <h4>What would you like for breakfast?</h4>
    <asp:checkboxlist id=food runat="server">
      <asp:listitem value="Cereal"/>
      <asp:listitem value="Eggs"/>
      <asp:listitem value="Pancakes"/>
    </asp:checkboxlist>     <h4>Feed me:<h4>
    <asp:radiobuttonlist id=when runat="server">
      <asp:listitem value="Now"/>
      <asp:listitem value="Later"/>
    </asp:radiobuttonlist>

    <asp:button type="submit" id="btnSubmit" onclick="ClickHandler"

text="Thank you!" runat="server" />

  </form>

</body>
</html>

7 3

Add a Page_Load event handler to the ASPX code you have just created which confirms the selections made in the following format:

Thank you very much _____.

You have chosen _____ for breakfast. I will prepare it for you _____.

<%@ Page Language="C#" runat="server" debug = true %>

<script runat="server">

  void ClickHandler(Object sender, EventArgs e)
{


    message.Text  = "Thank you very much " + name.Text;
    message.Text += ". You have chosen ";


    if (food.Items[0].Selected) message.Text += food.Items[0].Text + " ";
    if (food.Items[1].Selected) message.Text += food.Items[1].Text + " ";
    if (food.Items[2].Selected) message.Text += food.Items[2].Text + " ";


    message.Text += "for breakfast. I will prepare it for you " + Request.Form["when"] + ".";
    questions.Visible = false;
}

</script>

<html>
<head>
  <title>ASP.NET</title>
</head>
<body>

  <asp:label id=message runat=server />
  <form id=questions runat="server">

    <h4>Please enter your name:</h4>
    <asp:textbox id=name runat="server" /><br /><br />

    <h4>What would you like for breakfast?</h4>
    <asp:checkboxlist id=food runat="server">
      <asp:listitem value="Cereal"/>
      <asp:listitem value="Eggs"/>
      <asp:listitem value="Pancakes"/>
    </asp:checkboxlist>

    <h4>Feed me:<h4>
    <asp:radiobuttonlist id=when runat="server">
      <asp:listitem value="Now"/>
      <asp:listitem value="Later"/>
    </asp:radiobuttonlist>
    <asp:button type="submit" id="btnSubmit" onclick="ClickHandler" text="Thank you!"

runat="server" />

  </form>

</body>
</html>

7 4

Create a very basic virtual telephone using an ASPX file that displays a textbox and a button named "Call". Configure your ASPX file so that when you type a telephone number into your textbox and press "Call", you are:

  • presented with a message confirming the number you are calling
  • presented with another button called "Disconnect" that, when pressed, returns you to your opening page, leaving you ready to type another number

<%@ Page Language="c#" runat="server" debug = true %>

<script runat="server">

  void ClickHandler(Object sender, EventArgs e)
{


if (btnSubmit.Text == "Call")
{
      message.Text = "Calling: " + number.Text;
      btnSubmit.Text = "Disconnect";
      number.Enabled = false;
}
   else
{
      message.Text = "";
      btnSubmit.Text = "Call";
      number.Enabled = true;
}
}

</script>

<html>
<head>
  <title>Phone</title>
</head>
<body>

  <form id=questions runat="server">
    Please enter a telephone number:<asp:textbox id=number runat="server" /><br />

    <asp:button type="submit" id="btnSubmit" onclick="ClickHandler" text="Call"

runat="server" />
    <asp:label id=message runat=server />
  </form>

</body>
</html>

7 5

Using the switch construct, associate three particular telephone numbers with three names, so that when you press the "Call" button, your confirmation message contains the name of the person you are 'calling' rather than just the telephone number.

<%@ Page Language="c#" runat="server" debug = true %>

<script runat="server">

  void ClickHandler(Object sender, EventArgs e)
{

if (btnSubmit.Text == "Call")
{
string name;
switch (number.Text)
{
       case "6874923":
          name = "Jake";
          break;
        case "6874831":
          name = "Ewan";
          break;
        case "6874624":
          name = "Alessandro";
          break;
        default:
          name = "<unknown>";
          break;
}
      message.Text = "Calling " + name + " on " + number.Text;
      btnSubmit.Text = "Disconnect";
      number.Enabled = false;
}
    else
{
      message.Text = null;
      btnSubmit.Text = "Call";
      number.Enabled = true;
}
 }

</script>

<html>
<head>
  <title>Phone</title>
</head>
<body>

  <form id=questions runat="server">     Please enter a telephone number:<asp:textbox id=number runat="server" /><br />

    <asp:button type="submit" id="btnSubmit" onclick="ClickHandler" text="Call"

runat="server" />
    <asp:label id=message runat=server />
  </form>

</body>
</html>



Chapter Question
Number
Question Answer
10 1

Explain the role of the Page class in ASP.NET and describe what sort of things we can do with it.

When a browser makes an ASPX file request, the ASP.NET module (aspnet_isapi.dll) deals with it. The aspnet_isapi.dll then places the ASPX file that was requested into a new class definition defined in a namespace called ASP. This ASP class inherits from the Page class so the ASP.NET page has access to the useful functionality that the Page class provides.

The Page class is part of the System.Web.UI namespace. The Page class brings us a wealth of useful properties and methods that we can use on our ASP.NET pages. It also gives us access to a range of other objects created from classes in the System.Web namespace.

10 2

Write an ASP.NET page that returns the Windows name of your computer and the URL of the page that you are visiting.

<%@ Page Language="c#" %>

<script runat="server">
void Page_Load()
{
name.Text= Server.MachineName;
url.Text = Request.Url.ToString();
}
</script>

<html>
My computer is named: <b><asp:label id="name" runat="server" /></b><br />
My URL is: <b><asp:label id="url" runat="server" /></b>
</html>

10 3

(a) Write one ASP.NET page that prompts a user to enter a value for the radius of a circle then calculates its area (Area = Pi * (radius)²) and another ASP.NET page that prompts the user to enter the length of the radius and then calculates the circumference (circumference = 2*Pi*radius). Both pages should access the value of Pi (3.142) stored in application state.

(b) Repeat the above example storing the value of Pi in global.asax.

area.aspx

<%@ Page Language="c#" %>

<script language="c#" runat="server">

void Update(Object sender, EventArgs e)
{
  int IntInput = Convert.ToInt32(input.Text);
  double pi = Convert.ToDouble(Application["pi"]);
  area.Text = Convert.ToString(pi*IntInput*IntInput);
}
</script>

<html>
  <body>
    <form runat="server">
      Input = <asp:textbox id="input" runat="server" />
      <asp:button text="submit" runat="server" onclick="Update" /><br />
      the area is: <asp:label id="area" runat="server" />
    </form>
  </body>
</html>

circumference.aspx

<%@ Page Language="c#" %>

<script language="c#" runat="server">
void Update(Object sender, EventArgs e)
{
  int IntInput = Convert.ToInt32(input.Text);
  double pi = Convert.ToDouble(Application["pi"]);
  area.Text = Convert.ToString(pi*IntInput*2);
}
</script>

<html>
  <body>
  <form runat="server">
    Input = <asp:textbox id="input" runat="server" />
    <asp:button text="submit" runat="server" onclick="Update" /><br />
    the circumference is: <asp:label id="area" runat="server" />
  </form>
</body>
</html>

a. Setting variable in application state

<html>
  <body>
    <%
    Application("pi") = "3.142"
    %>
  </body>
</html>

b. Setting Pi in global.asax

<%@ Page Language="c#" %>
<script language="c#" runat="server">
void Application_OnStart()
{
  Application["pi"] = "3.142";
}
</script>

10 4

Using session variables implement a shopping cart that lets you add up to five items from a dropdown listbox and displays:

(a) The total number of items selected

(b) A list of all the items in the cart

There should also be a means of emptying all the items contained in the cart.

<%@ Page language="c#"%>
<script language="c#" runat="server">
    void AddClick(object sender, EventArgs e)
{
if (Session["BasketCount"] != null && (int)Session["BasketCount"] < 5)
{
  int i = (int)Session["BasketCount"];
  i++;
  Session["BasketCount"] = (object)i;


   Session["BasketItem"] = Request.Form["list1"];
    string [] Items = new string[5];

    int n;

    n = (int)Session["basketCount"] - 1;
    Items[n] = Request.Form["list"];
    {
      foreach (string item in Items)
      shopping.Text = shopping.Text + item + "<BR>";
    }
}
if (Session["BasketCount"] == null)
{
 Session["BasketCount"] = 1;
}


}
  void EmptyClick(System.Object sender, System.EventArgs e)
{
Session["BasketCount"] = 0;
    Session["BasketItem"] = null;
    shopping.Text = null;
}



</script>

<html>
  <body>

    <form id="BasketForm" method="post" runat="server">
      <asp:dropdownlist id="list" runat="server">
        <asp:listitem>bread</asp:listitem >
        <asp:listitem >fish</asp:listitem >
        <asp:listitem >chillies</asp:listitem >
        <asp:listitem >olives</asp:listitem >
        <asp:listitem >Turnip juice</asp:listitem >
      </asp:dropdownlist >

      <asp:Button id="Add" OnClick="AddClick" runat="server" Text="Add"/>
      <asp:Button id="Empty" OnClick="EmptyClick" runat="server"
Text="Empty"/>
      <br />
      basketItems: <br/> <asp:label id="shopping" runat="server" />
      <br />Number of items : <%=Session["BasketCount"]%>
      <br />
    </form>
  </body>
</html>

10 5

Create an ASP.NET page that contains textboxes in which a user can enter his name, address and telephone number. Using cookies, display this information on a separate ASP.NET page.

Code for setting cookie:

<%@ Page Language="c#" %>
  <script language="c#" runat="server">

    public void Click(object sender, EventArgs e)
    {
      HttpCookie NameCookie = new HttpCookie("Name");
      HttpCookie AddressCookie = new HttpCookie("Address");
      HttpCookie PhoneCookie = new HttpCookie("Phone");

      NameCookie.Value = name.Text;
      AddressCookie.Value = address.Text;
      PhoneCookie.Value = phone.Text;

      Response.Cookies.Add(NameCookie);
      Response.Cookies.Add(AddressCookie);
      Response.Cookies.Add(PhoneCookie);
    }
  </script>

<html>
  <body>
    <form id="CookieForm" method="post" runat="server">
      name:       <asp:textbox id=name runat="server"/><br />
      address:    <asp:textbox id=address runat="server"/><br />
      Telephone:  <asp:textbox id=phone runat="server"/><br />
      <asp:button id=MyButton runat="server" text = "Submit" OnClick="Click"/>
    </form>
  </body>
</html>

Code for retrieving cookie:

<%@ Page Language="c#" %>
<script language="c#" runat="server">
  void Page_Load(object source, EventArgs e)
  {
    Response.Cache.SetExpires(DateTime.Now);
    Namelbl.Text= Request.Cookies["Name"].Value;
    Addresslbl.Text= Request.Cookies["Address"].Value;
    Phonelbl.Text= Request.Cookies["Phone"].Value;
  }
</script>

<html>
  <body>
    Your name is: <asp:label id="Namelbl" runat="server" /><br />
    Your address is: <asp:label id="Addresslbl" runat="server" /><br />
    Your Telephone number is: <asp:label id="Phonelbl" runat="server" />
   </body>
</html>



Chapter Question
Number
Question Answer
11 1

Describe a situation in which you would use each of the following and state why that choice is the best:

  • arrays
  • arraylists
  • hashes
  • sorted lists

Arrays are used when you want a quick and easy to build list that you will not need to resize or add items into the middle of the list.

ArrayLists are used when you need an automatically resizable list that also allows items to be inserted into or removed from the middle, and performance is not an issue.

Hashes are used when you need to do fast lookups from one piece of data to another. The data is not sorted.

Sorted lists are most useful when we have to sort a list of key/value pairs for which the ordering of the key is what matters, rather than the order of the values. For example, we might use a sorted list to hold entries in a dictionary.

11 2

 

<%@ Page language="c#" %>

<script runat="server" language="c#">
string[] AnimalArray = new string[5];

void Page_Load()
{
    AnimalArray[0] = "Dog";
    AnimalArray[1] = "Cat";
    AnimalArray[2] = "Elephant";
    AnimalArray[3] = "Lion";
    AnimalArray[4] = "Frog";

    MyDropDownList.DataSource = AnimalArray;
    MyDropDownList.DataBind();
}

void Alphabet(object sender,EventArgs e)
{
    if (Request.Form["sort"] == "alphabetical")
    {
    Array.Sort(AnimalArray);
    }
else
    {
    Array.Reverse(AnimalArray);
    }
    MyDropDownList.DataBind();
}
</script>

<html>
<form runat="server" >
  <asp:dropdownlist runat="server" id="sort">
    <asp:listitem>alphabetical</asp:listitem>
    <asp:listitem>reverse</asp:listitem>
  </asp:dropdownlist>
  <asp:button text="submit" runat="server" OnClick="Alphabet" />
  <asp:dropdownlist id="MyDropDownList" runat="server" /><br /><br />

  <hr />
</form>
</html>

11 3

Bind a dropdown list to an array containing five colors, then create a submit button that displays a line of etxt in the selected color when clicked.

<%@Page language="c#" %>

<script runat="server" language="c#">
void Page_Load(object sender, EventArgs e)
{
  if (!(Page.IsPostBack))
  {
    string StrColor;
    string [] colorArray = new string[5];
    colorArray[0] = "mediumorchid";
    colorArray[1] = "firebrick";
    colorArray[2] = "cornflowerblue";
    colorArray[3] = "sienna";
    colorArray[4] = "deepskyblue";

    MyDropDownList.DataSource = colorArray;
    MyDropDownList.DataBind();
  }
}

void ChangeColor(object sender, EventArgs e)
{
  string color;
     color = MyDropDownList.SelectedItem.Value;
  label.Text = "<font color=" + color + ">This is your color</font>";
}
</script>

<html>
<form runat="server" >
  <asp:dropdownlist id="MyDropDownList" runat="server" />
  <asp:Button id="change" text="pick a color" runat="server" OnClick="ChangeColor" />


</form>
<asp:label id="label" runat="server" />
</html>

11 4

Using a hashtable, display a list of user names in a dropdown list with a submit button that displays the corresponding user ID when pressed. On the same page add two textboxes in which a user can enter new user names and IDs into the hashtable.

The newly created user name should appear in the dropdown box, and the corresponding user ID should be displayed when the submit button is clicked.

<%@Page language="c#" debug="true"  %>

<script runat="server" language="c#">
  Hashtable Users = new Hashtable();

  void Page_Load(object sender, EventArgs e)
  {
    Users["RedmanJ"] = "Redman Jones";
    Users["PaintM"] = "Painter Mo";
    Users["MirrorD"] = "Mirror Dede";
    Users["BabaF"] = "Baba Farooq";

    if (!(Page.IsPostBack))
    {
      foreach (DictionaryEntry Item in Users)
      {
        ListItem newListItem = new ListItem();
        newListItem.Text = Item.Value.ToString();
        newListItem.Value = Item.Key.ToString();
        myDropDownList.Items.Add(newListItem);
      }
    }
 }

  void Add(object sender, EventArgs e)
  {
    Users[userID.Text] = name.Text;

    ListItem newListItem = new ListItem();

    newListItem.Text = name.Text;
    newListItem.Value = userID.Text;
    myDropDownList.Items.Add(newListItem);
  }

  void Click(Object sender, EventArgs e)
  {
   myLabel.Text = myDropDownList.SelectedItem.Value;
  }

</script>

<html>
  <form runat="server">
    <asp:dropdownlist id="myDropDownList" runat="server" />
    <asp:button id="myButton" runat="server" text="Get user ID" Onclick="Click" />
    <br /><br /><br /><br /><br /><br />
    Add user: <asp:textbox id="name" runat="server" />
    ID: <asp:textbox id="userID" runat="server" />
    <asp:button id="addusr" runat="server" text="Add User" Onclick="Add" /><br /><br />
    <hr />
    <asp:Label id="myLabel" runat="server" text="" />
  </form>
</html>

11 5

Create an ASPX page that takes value entered via a textbox and searches for it in this sorted list:

mySortedList("armadillo")="any of a family ... small bony plates"
mySortedList("amaryllis")="an autumn-flowering ... Hippeastrum or Sprekelia)"
mySortedList("zebra")="any of several fleet ... white or buff"
mySortedList("artichoke")="a tall composite herb ... cooked as a vegetable"
mySortedList("aardvark")="a large burrowing ... termites and ants"

The results of the search should be displayed on the page.

<%@Page language="c#" debug="true"  %>

<script runat="server" language="c#">
  SortedList mySortedList = new SortedList();


  void Page_Load(object source, EventArgs e)
     {
    mySortedList["armadillo"]="any of a family ... small bony plates";
    mySortedList["amaryllis"]="an autumn-flowering ... Hippeastrum or Sprekelia)";
    mySortedList["zebra"]="any of several fleet ... white or buff";
    mySortedList["artichoke"]="a tall composite herb ... cooked as a vegetable";
    mySortedList["aardvark"]="a large burrowing ... termites and ants";
  }

  void search(object source, EventArgs e)
    {
    foreach (DictionaryEntry Item in mySortedList)
      {
      if (input.Text == Item.Key.ToString())
        {
        result.Text = "<b>" + Item.Key + "</b>:  " + Item.Value;
        }
      }
     }
</script>

<html>
<asp:label id="MyLabel" runat="server" />
  <form runat="server">
    <b>search for: </b><asp:textbox id="input" runat="server" />
    <asp:Button id="enter" onClick="search" runat="server" text="search!"/>
  </form>
  <asp:label id="result" runat="server" />
</html>