I have created three different example programs so that I can talk about some additional topics in the area of WebForms and Web form application development. I will present these three applications and then explain some of the salient features of them. Shakespeare ProgramI had a program magically appear on one of my Web sites. Actually, I use this Web site at www.eKidPlace.com to give my students a place were they can freely develop their own ideas and post them to a live Web site. This program surfaced after about a week of covering the topic of WebForms, and I thought it was so cool I decided to share it with you. A couple of things are evident in this program. The program gives users the opportunity to generate verbal insults in the style of Shakespeare. The user can either select from a list of preset words, put them in whatever order they want and have the insult generated, or an insult can be generated randomly . The code in Listing 11.3 is the .ASPX code that makes the program work. It is fairly simple and straightforward. There are several Labels and three DropDownList objects, and finally one Button . The DropDownList objects contain the word and phrase categories that are used to form the Shakespeare insults. The first list has a lot of adjectives that modify the rest of the insult. In the code you will notice that I have not included the entire list that is included in either of these drop-down links because each of them has almost fifty entries. The second and third drop-down lists contain the additional parts of speech that make up the remainder of the insult. In Figure 11.1 you can see the application after it has generated a random insult. Figure 11.1. This application makes extensive use of the DropDownList control.
Listing 11.3 The .ASPX Code for the Shakespeare Program<body bgColor="#6666ff" MS_POSITIONING="FlowLayout"> <form id="Form1" method="pozst" runat="server"> <p> <asp:Label id="Label1" runat="server" ForeColor="White" Height="55px" Width="575px" Font-Size="XX-Large">Shakespeare Insult Generator</asp:Label> </p> <p> <asp:label id="Label2" runat="server" ForeColor="White" Font-Size="Medium">Or, make your own!</asp:label> </p> <p> <asp:Label id="Label3" runat="server" ForeColor="White" Font-Size="Medium">Let us randomly generate one for you. . .</asp:Label> </p> <p> <asp:Label id="Label4" runat="server" ForeColor="White" Height="54px" Font-Size="Medium">The Bard was certainly well-known for his wordy wit. Now, with our handy-dandy instant insult machine, you can zing your friends like a real Elizabethan thespian!</asp:Label> </p> <p> <asp:Button id="Button1" runat="server" Text="Generate Random!"> </asp:Button> <asp:Label ID="Label5" runat="server" Text=" Your insult here..." ForeColor="Yellow" Font-Size="Medium">Your insult here...</asp:Label> </p> <p> <HR width="100%" SIZE="1"> <P> </P> <p> <asp:Button id="Button2" runat="server" Text="Generate From List!"> </asp:Button> <asp:DropDownList id="DropDownList1" runat="server"> <asp:ListItem Value="artless">artless</asp:ListItem> <asp:ListItem Value="bawdy">bawdy</asp:ListItem> . . . <asp:ListItem Value="weedy">weedy</asp:ListItem> <asp:ListItem Value="yeasty">yeasty</asp:ListItem> </asp:DropDownList> <asp:DropDownList id="DropDownList2" runat="server"> <asp:ListItem Value="base-court">base-court</asp:ListItem> <asp:ListItem Value="bat-fowling">bat-fowling</asp:ListItem> . . . <asp:ListItem Value="unchin-anouted">unchin-anouted</asp:ListItem> <asp:ListItem Value="weather-bitten">weather-bitten</asp:ListItem> </asp:DropDownList> <asp:DropDownList id="Dropdownlist3" runat="server"> <asp:ListItem Value="apple-john">apple-john</asp:ListItem> <asp:ListItem Value="baggage">baggage</asp:ListItem> . . . <asp:ListItem Value="whey-face">whey-face</asp:ListItem> <asp:ListItem Value="wagtail">wagtail</asp:ListItem> </asp:DropDownList> <P> </P> <p> <asp:Label id="Label6" Runat="server" Text=" Your insult here" ForeColor="Yellow" Font-Size="Medium"> Your insult here</asp:Label> </p> </form> </body> The thing I want to talk about here is the use of the Randomize() and Rnd() methods in the code you can see ahead in Listing 11.4. The first thing in the Rnd() method is what is used to retrieve a random number. The Rnd() method returns a value between 0 and 1. Although it does have the possibility of returning 0, it never answers 1. You use the Rnd() method to retrieve the next random number in the series. Your code can do this in a couple of different ways. For instance, the following code fragment sets an integer named nSomeInteger to a value between 0 and 47. nSomeInteger = Int((Rnd() * 48)) The number that is multiplied by Rnd() determines the range of numbers that you get back. Notice that I used the Int() method so that the number I get back is actually an integer rather than a floating point number. Rnd() by default returns a floating point number, so to get an integer I need to make sure that it is converted. The Rnd() method can possibly take one of three optional parameters. If the parameter is less than 0, the Rnd() method returns the same number every time, but it uses this parameter (whatever was passed in) as the seed. If the number passed to the Rnd() method is 0, it returns the most recently generated number. If the number passed to the Rnd() method is greater than 0, the next number returned is whatever the next number in the sequence is. If you don't give it an argument, it just returns the next random number in the sequence. One of the difficulties with random number generators is that they, ironically enough, always follow a set sequence. Or more correctly, they follow a sequence that results from the mathematical operations performed during the creation of the next random number. It is not like it goes through a set list of random numbers before returning one to you. A set of mathematical operations are performed on statically stored variables to create what really is a pseudo-random number generator. What this means is that if you use the Rnd() method in an application, it returns the same sequence of numbers every time you use it. So every time you run the application, your random numbers are exactly the same as they were the last time you ran the application, and it will not seem then that the numbers are truly random. What is needed is a way to alter the start of the random number sequence. This is where the Randomize() method comes in. The Randomize() method can be used without any arguments, and if you use it without any arguments it generates a seed for the random number sequence generator based on the system timer. You can, however, specify the seed value as an argument to the randomize method as the following code fragment shows. Now take a look at the code in Listing 11.4 and in the Button1_click method you will see that three random numbers are retrieved after the Randomize() method is called. This produces a different result each time users come through and use the application. The following code seeds the random number generator: ' Seed the random number generator with the value of 15 Randomize(15) Listing 11.4 The VB Code to Create the Shakespeare InsultsPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim dFirst As Double Dim dSecond As Double Dim dThird As Double Randomize() dFirst = (Rnd() * 48) Dim strWord1 As String strWord1 = DropDownList1.Items.Item(dFirst).Text dSecond = (Rnd() * 48) Dim strWord2 As String strWord2 = DropDownList2.Items.Item(dSecond).Text dThird = (Rnd() * 47) Dim strWord3 As String strWord3 = Dropdownlist3.Items.Item(dThird).Text Label5.Text = "Thou " + strWord1 + " " + strWord2 + " " + strWord3 + "!" End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Label6.Text = "Thou " + DropDownList1.SelectedItem.Text + " " + DropDownList2. SelectedItem.Text + _ " " + Dropdownlist3.SelectedItem.Text + "!" End Sub Guessing GameEach semester I teach several programming classes, and now they include classes on ASP.NET. I usually use an example application that helps me demonstrate the use of the Convert class. The application I use is a guessing game. The program starts off and generates a random number. Then, the user tries to guess the number. It says whether the guess is to low or to high, or says that the user is correct. The ASPX code for this application is very, very simple, as you can see in Listing 11.5. Several labels in the code let the user know the status of his or her guessing. You will notice also that at the bottom of the code there are two hidden labels: Label4 and Label5 . They are hidden because they each have the visible attribute set to false. I will talk about why I put these in and how I use them later on when I discuss Listing 11.6. Figure 11.2 shows the application running after the user has made a single guess. Figure 11.2. This guessing game has two hidden fields to persist some data.
Listing 11.5 .ASPX Code That Includes Two Hidden Labels<body MS_POSITIONING="FlowLayout" bgColor="blue"> <form id="Form1" method="post" runat="server"> <P> <asp:Label id="Label1" runat="server" Width="542px" Height="43px" Font-Size="XX-Large" ForeColor="White">The Cool Guessing Game</asp:Label> </P> <P> <asp:Label id="Label2" runat="server" Width="352px" Height="19px" Font-Size="Medium" ForeColor="Yellow"></asp:Label> </P> <P> <asp:Label id="Label3" runat="server" Font-Size="Medium" ForeColor="Yellow">Your Guess: </asp:Label> <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> <asp:Button id="Button1" runat="server" Text="Check The Answer"> </asp:Button> <asp:Label id="Label4" runat="server" Visible="False"></asp:Label> <asp:Label id="Label5" runat="server" Visible="False"></asp:Label> </P> </form> </body> If you look at the code in Listing 11.6 you can see two methods: the Page_Load() and the Button1_Click() methods. You can also see two member variables that keep track of the randomly selected number the user needs to guess and the number of guesses that the user has made. In the Page_Load method you will notice that two pieces of code are executed, depending on whether this is a PostBack. The IsPostBack property is checked to make the determination. If this is not a PostBack, and this is the first time the application has run, the random number is generated by a call to the Randomize() method and then the Rnd() method. You might notice that I checked to make sure that the randomly generated number is not greater than 20. You are probably wondering why I do that, because, based on the formula I use in this method, it should never generate the value of 20. Although this theoretically is true, during testing I found that the Rnd() method can possibly return a value of 1, therefore giving me in this case a value of 20. I am not sure whether this is a bug in the Rnd() method or whether the documentation is somehow incorrect. In any case, I added this small piece of code to ensure that the value of the randomly generated number is not greater than 20. If this is not a PostBack, I set the value of m_nTheNumber and m_nNumberOfGuesses to the values that are stored in my two hidden labels. Now why would the values be stored in the hidden labels? Values that are stored in the hidden labels persist between PostBacks, whereas values in member variables do not. Therefore, if I want to persist values in member variables, I need to somehow first store their values and labels, then retrieve them when the page is loaded next. The next thing to consider is the Convert class, which you can see in this Page_Load() method. The Convert methods are used to convert any base type to any other base type. For instance, I may want to convert a string to an integer, or I might want to convert a double to a string. In the case of this application, I am converting strings (which are found in Label4.Text and Label5.Text ) to a 32-bit integer. The way I do this is I say my integer is equal to Convert.ToInt32( TheString ) . One important thing to note, though, is that the Convert methods can possibly throw an exception. For instance, if you are converting from a string to an integer and the string contains nothing, then the Convert.ToInt32() method throws an exception. It may appear that I am not handling exceptions in this code, but the fact is that my code is setting the text in the labels each time, and I therefore know that the label text will contain valid numeric representations. This is also example code and I don't want the concept to be cluttered with exception code. Now take a look at the Button1_Click() method. This method takes whatever string value users have placed into the TextBox1 object and converts it into an integer. Once again, it uses the Convert.ToInt32() method. It then compares the user's guess with a randomly generated number, and if they are the same it alerts the user by setting text in the label that the answer is correct. If the guess is too high it says so; if the guess is too low it reports that, as well. Note that at the very end of this method the value of m_nNumberOfGuesses is set into Label5 . This is so that Label5 will contain the accurate number of guesses. Listing 11.6 Code to Display the Information and Interact with the UserDim m_nTheNumber As Integer Dim m_nNumberOfGuesses As Integer Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not IsPostBack Then Randomize() m_nTheNumber = (Rnd() * 20) + 1 If m_nTheNumber > 20 Then m_nTheNumber = 20 End If m_nNumberOfGuesses = 0 Label2.Text = "I have a number from 1 to 20. Try to guess it..." Else m_nTheNumber = Convert.ToInt32(Label4.Text) m_nNumberOfGuesses = Convert.ToInt32(Label5.Text) End If Label4.Text = Str(m_nTheNumber) Label5.Text = Str(m_nNumberOfGuesses) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim nTheirGuess As Integer nTheirGuess = Convert.ToInt32(TextBox1.Text) m_nNumberOfGuesses = m_nNumberOfGuesses + 1 TextBox1.Text = "" If nTheirGuess = m_nTheNumber Then Label2.Text = "You got it in " + Str(m_nNumberOfGuesses) + _ " tries. The number was " + Str(m_nTheNumber) + "." ElseIf nTheirGuess > m_nTheNumber Then Label2.Text = "Your guess (guess number " + Str(m_nNumberOfGuesses) + ") was too high." Else Label2.Text = "Your guess (guess number " + Str(m_nNumberOfGuesses) + ") was too low." End If Label5.Text = Str(m_nNumberOfGuesses) End Sub Temperature CalculatorThe last application in this chapter is the temperature calculator. This application is good for showing you how to make decisions based on radio buttons , convert from text to integers, and format output strings for users. Look first at the ASPX code in Listing 11.7. The code has several Labels to give users instructions and feedback. It has a single TextBox that enables a user to type in the temperature. It has a set of RadioButtons that enables users to specify which type of temperature scale they are using: Fahrenheit, Celsius, or Kelvin. And lastly, there is a calculate Button. You can see the application running in Figure 11.3. Figure 11.3. The application converted 32 degrees Fahrenheit to 0 Celsius and 273 Kelvin.
Listing 11.7 The .aspx Code for the Temperature Conversion Program<body MS_POSITIONING="FlowLayout" bgColor="blue"> <form id="Form1" method="post" runat="server"> <P> <asp:Label id="Label1" runat="server" Width="542px" Height="43px" Font-Size="XX-Large" ForeColor="White">The Temperature Converter</asp:Label> </P> <P> <asp:Label id="Label2" runat="server" Font-Size="Medium" ForeColor="Yellow">Temperature: </asp:Label> <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> <asp:Label id="Label4" runat="server" Width="468px" Height="20px" Font-Size="Medium" ForeColor="Yellow"></asp:Label> </P> <P> <asp:Label ID="Label3" Runat="server" Font-Size="Medium" ForeColor="Yellow"> In which scale is the temperature that you entered?</asp:Label> <br> <asp:RadioButton id="RadioButton1" runat="server" Text="Farenheit" GroupName="scale" Checked="True"></asp:RadioButton> <br> <asp:RadioButton id="RadioButton2" runat="server" Text="Celcius" GroupName="scale"></asp:RadioButton> <br> <asp:RadioButton id="RadioButton3" runat="server" Text="Kelvin" GroupName="scale"></ asp:RadioButton> </P> <P> <asp:Button id="Button1" runat="server" Text="Calculate"></asp:Button> </P> </form> </body> Now look at the code in Listing 11.8. I have shown only a single method: the Button1_Click() method. Notice that the first thing I do is convert the value in the TextBox to a double. Then I declare three double variables for Fahrenheit, Celsius, and Kelvin. I use the Checked property of each RadioButton to determine which one has been selected. As you can see, the statement if( RadioButton1.Checked ) is what determines that RadioButton1 has been selected. Inside this if statement, I convert the value (which is Fahrenheit) to Celsius by performing some simple math. I then convert Celsius to Kelvin by simply adding 273. And then I format the Label text to give the user the necessary feedback. If RadioButton2 has been selected, I convert the value (which is Celsius) to Fahrenheit. I then convert the value to Kelvin by adding 273. And then I display the results in the Label . And finally, if RadioButton1 or RadioButton2 have not been checked, I know that the application is to convert from Kelvin to Fahrenheit and Celsius. I perform the necessary calculations, and set the Label text to indicate the results. Listing 11.8 The Code That Converts the TemperaturePrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim dValue As Double dValue = Convert.ToDouble(TextBox1.Text) Dim dFarenheit As Double Dim dCelcius As Double Dim dKelvin As Double If RadioButton1.Checked Then dCelcius = ((dValue - 32) * 5) / 9 dKelvin = dCelcius + 273 Label4.Text = "degrees farenheit=" + Str(dCelcius) + " degrees celcius, " + Str( dKelvin) + _ " degrees kelvin" ElseIf RadioButton2.Checked Then dFarenheit = ((9 * dValue) / 5) + 32 dKelvin = dValue + 273 Label4.Text = "degrees celcius=" + Str(dFarenheit) + " degrees farenheit, " + Str( dKelvin) + _ " degrees kelvin" Else dCelcius = dValue - 273 dFarenheit = ((9 * dCelcius) / 5) + 32 Label4.Text = "degrees kelvin=" + Str(dFarenheit) + " degrees farenheit, " + Str( dCelcius) + _ " degrees celcius" End If End Sub |