1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 3 pot

90 230 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 90
Dung lượng 1,29 MB

Nội dung

<html> <head> <title>Do While Loop Example</title> </head> <body> <asp:label id="message1" runat="server"/> </body> </html> 2. View this page in your browser as shown in Figure 4-10 and click the Refresh button several times: Figure 4-10 How It Works We started by declaring a variable that will hold the result of the diceRoll. Then we put some text into Message1.text. This line mainly demonstrates a line before a loop – it will only be executed once. When you start building complex pages you will need to keep a clear idea of what is inside and outside of the loop: <script runat="server"> void Page_load() { Random r = new Random(); int diceRoll; message1.Text = "Lets get started. <br>"; Then we run the loop. If the last dice roll was anything other than a 6, we want to roll again, so we use the inequality operator to tell C# to keep running the loop, so long as the dice roll is not equal to six. We do this because we want the loop to stop once we have a six. We finish with a demonstration of a line after the loop do { 153 Control Structures and Procedural Programming diceRoll = Convert.ToInt32(r.Next(6)) + 1; message1.Text = message1.Text + "Rolled a: " + diceRoll + "<br />"; } while (diceRoll != 6); } message1.Text += "There is our six."; </script> When diceRoll equals six, it will stop and not execute the contents of the loop, instead jumping to the next statement beyond the loop. Modulo example You came across the modulo (%) operator in the last chapter, and early on in this chapter. Recall that modulo returns the remainder of a division. You can refer to these sections to jog your memory about what modulo can do. Here we will apply this operator to our dice example. Open TIO- WhileLoop.aspx , change the code as shown and save as Demo-Modulo.aspx. This modification will give the user an encouragement message with every third roll: <%@ Page Language="C#" debug="true"%> <script runat="server"> void Page_Load() { // demo of modulo where every third try displays an encouraging message Random objRandom = new Random(); int DiceRoll = 0; byte bytRollCounter = 0; Message1.Text = "Lets begin. We'll keep trying until we get a six.<br/>"; while (DiceRoll != 6) { // check if we need to show the 'keep trying' message if(bytRollCounter%3 == 0 && !(bytRollCounter==0)) { Message1.Text += " Keep trying! <br>"; } // End If bytRollCounter +=1; DiceRoll = Convert.ToInt32(objRandom.Next(6)) + 1; Message1.Text += "Rolled a: " + DiceRoll + "<br />"; } // end Loop Message1.Text += "Got it. Press page refresh to try again."; } //end void Page_Load() </script> Use do while when actions within the loop absolutely have to occur at least once no matter what the result of the expression. Use while when there are actions within the loop that should not execute if the expression is false. 154 Chapter 4 <html> <head> <title>Modulo example (using a While Loop)</title> </head> <body> <asp:label id="Message1" runat="server"></asp:label> </body> </html> Test it with several refreshes until a try takes at least three rolls. In this code, we start by creating a variable that will count our rolls. We can use byte data type with the assumption that we will roll a six in less then 255 tries. Then in each loop, we increase the value in bytRollCounter. Then we check if bytRollCounter is evenly divisible by 5, in other words the remainder is zero. If true, we concatenate the encouragement message as shown in Figure 4-11: Figure 4-11 The foreach in Loop C# has a cousin of the for statement named foreach. It works in a similar way to for, except that it's only used for elements inside an array or a collection. It is a lot like w hile, since we don't have to know the number of members in the collection. We've met several collections in the last chapter: Arrays, ArrayLists, Hashtables, and SortedLists. For example, we could read all elements of a simple array into a label as follows (see the download file named Demo-forEach.aspx) void page_Load() { string[] arrCities = new string[3]; arrCities[0]=("London"); arrCities[1]=("Paris"); arrCities[2]=("Munich"); foreach (string item in arrCities) { 155 Control Structures and Procedural Programming lblOut.Text += item + "<BR>"; } //end foreach } //end page_Load() It looks almost identical to the for structure. The only difference is that you don't have to specify the number of items you want to loop through; C# will simply start with the first item in the array and then repeat the loop until it reaches the last item. Summary This chapter introduced C# control structures, the tools used to determine the order of execution of lines of code. Sometimes we use a branching control to choose only one of several alternatives of lines to execute. At other times, we use a looping structure to consecutively repeat lines of code. We may also use jumping structures, which are covered in the next chapter. We started with operators. The equal sign ( =) assigns a value into a variable or object property. We can also use += to make an addition to the existing value in a variable or property. We also covered the concatenation operator, +, which appends a string of text onto an existing string of text. We then covered the basic math operators for addition, subtraction, etc. Always keep in mind the precedence of execution if you have many terms: start in the parentheses, work left to right with multiplication and division, then left to right with addition and subtraction. Then C# moves to the next higher level of parentheses. Using parentheses often makes the calculation easier to write and maintain. Modulo provides the remainder value from a division. There are three commonly used logical operators. && means AND, which uses two complete expressions and requires both to be true in order to return a value of true. || means OR, which also uses two complete expressions but only one has to be true in order to get an overall answer of true. ! means NOT which reverses the logical value of whatever follows it (if the expression is complicated, it is best to put it in parenthesis). if allows us to execute just one of two sets of code. The simplest form only takes one line, but can only execute one statement for the true case. Adding the braces allows multiple lines to be executed in the case of the expression being true. If you also use else then you can execute lines in the case where the expression resolves to false. When you have many possible values for a variable then you can use the switch structure rather than heavily nested if structures. When looping you must decide on (if you know, at the time the loop starts) the number of loops you intend to execute. If you can determine the number of loops needed to be performed, use the for loop structure. Be careful about the lines that go in the loop and the ones that should be before or after the loop. If you do not know the number of iterations required, you use the while or do loops that perform a test at each cycle and either loop again, or stop. It never executes a loop if the expression is false. The d o while looping structure always executes at least once because the test is not performed until the end of the first loop. If you need to loop through code that affects each member of a collection ( arraylist, hashtable, etc.) then use foreach in looping structure. C# will automatically perform the loop once on each member of the collection. This chapter covered branching and looping structures. The next chapter will cover jumping structures 156 Chapter 4 Exercises 1. For each of the following Boolean expressions, say for what integer values of A each of them will evaluate to true and when they will evaluate to false: ❑ NOT A=0 ❑ A>0ORA<5 ❑ NOTA>0ORA<5 ❑ A>1ANDA<5ORA>7ANDA<10 ❑ A<10ORA>12ANDNOTA>20 2. Suggest a loop structure that would be appropriate for each of the following scenarios and justify your choice: ❑ Displaying a set of items from a shopping list stored in an array ❑ Displaying a calendar for the current month ❑ Looking through an array to find the location of a specific entry ❑ Drawing a chessboard using an HTML table 3. Write a page that generates ten random numbers between two integers provided by the user in text boxes. 157 Control Structures and Procedural Programming 5 Functions In the last chapter, we mentioned three ways to sequence the execution of C# code within your ASP.NET page: branching, looping, and jumping. We have already discussed branching and looping and will now discuss jumping structures. Jumping is used when we want to leave the execution of our main code midway and jump over to execute another block of code. After executing the block, we return to our main code. Jumping makes it easier to create and maintain code for many reasons, and is therefore, an important skill for programmers. This chapter will cover the following topics: ❑ Defining and using simple functions ❑ Passing parameters to functions ❑ Using the return value from a function ❑ Passing parameters by value and by reference ❑ Good practices Overview Jumping structures allow the programmer to halt the execution of the main code and jump to another block of code. This block of code is called a function. ("Later, when we look at classes in Chapter 7, we will also refer to it as a method.") After the function has run, execution returns to the main code again. Functions will come in handy as you write more and more ASP.NET code, and begin to find that you need to use the same code in more than one place. Then you just write a function containing that particular code, and execute it as many times as you like. For example, you may have written a function called ShowOrder() that displays the goods that a customer has ordered. For C# to display this output, you don't have to rewrite or copy all of that code into the body of code. Instead, just have C# jump out of your current code, execute the ShowOrder() function, and then come back and continue executing the original code. Modularization The process of dividing one large program into several smaller, interlocking parts is called modularization. This term can be applied to several instances; for example, we already modularize our page into an HTML section and a script section. Within the script section, we can further modularize our code by creating functions as described in this chapter. Later, we will discuss moving code to its own page (covered in Chapter 12). An additional level of modularization is to move code out into objects that exist completely independently of the page, something that we will cover in Chapter 7. Let's take a moment to discuss the advantages of modularization. ❑ Easier to write: Instead of trying to organize an entire project in your mind, you can focus on just code that performs a specific job in a module. Then, you can move on to the specific job of another module. Many studies show that this type of programming, if properly planned, results in better code with development done sooner and cheaper. ❑ Easier to read and maintain: A programmer looking at the code for the first time can quickly grasp the objectives of each section if sections are independent. Not only is each module clearer, but a reader also has an easier time tracing the flow of a program from section to section. ❑ Facilitates testing and troubleshooting: You can test modules independently without worrying about errors introduced by the rest of the code. If you know a particular module works without error and then plug it into an untested module, you can narrow down the causes of any errors to the untested module or to the interface between the two. ❑ Multiple programmers can work together: Each group of programmers can focus on one objective that will be self-contained within a module. The important management issue is to have each module clearly defined in terms of its purpose, input, and output. In more advanced forms of modularization (particularly objects), different teams can even work in different languages. .NET provides for a common interface for modules to interchange information. ❑ Code reuse: Many tasks (such as the display of a shopping cart's current value) must be repeated at many points on a page or on a Web site. If you put 100 lines of code in one module and call it ten times in your code, that's 890 lines of code you've saved. ❑ Good stepping stone: Ultimately, you will want to use the more sophisticated techniques of code-behind and objects, but before you get there, it is a good practice to think and act modular within your simple script tags. Programmers must keep their designs straight especially if their code calls functions. These calls can be several layers deep and are easy to conceptualize with a diagram such as Figure 5-1: 160 Chapter 5 Figure 5-1 Defining and Using Functions Functions are easy to write; let's look at a simple example where we write a function in our Web page and call it. We'll start with a basic function that doesn't exchange any information with the rest of the page and then move on to more complex code. Try It Out Defining and Using a Simple Function 1. Create a new ASP.NET page called SimpleFunction.aspx and save it in your Ch05 folder. 2. Add the following code to the file in the All view: <%@ Page Language="C#" Debug="true" %> <script runat="server"> void Page_Load() { lblMessage.Text = "First Line"; InsertLinebreak(); lblMessage.Text += "Second Line"; InsertLinebreak(); lblMessage.Text += "Third Line"; InsertLinebreak(); } void InsertLinebreak() { lblMessage.Text += "<br><hr>"; } </script> <html> <head> <title>Simple Function Example</title> </head> 161 Functions [...]... fact, a function, although of a special type because ASP.NET already knows about it without any help from us Inside ASP.NET, there are several functions that can be executed at times without a call from your code Page_Load(), for example, is automatically called whenever a page is loaded from the server These pre-defined functions are associated with events and will be discussed in the next chapter... Text property of a TextBox Web control) Let's try this out with an example We're going to expand on our previous example here by giving InsertLinebreak() two parameters to work with These will determine the number and width of horizontal rules to generate between lines Try It Out Functions with Parameters 1 Create a new ASP.NET page called FuncWithParameters.aspx and save it in your Ch05 folder 2 Add... } 3 The second function is named JoinWithDash(), and its return value will be put into an object's property JoinWithDash() takes two text strings and concatenates them with a dash in the middle Input parameters and the output are of type string We use JoinWithDash() to join the two strings in the textboxes and then we display the results using lblJoinedText: // Returns a concatenation of two texts with. .. value="2">2 Lines 3 Lines 3 166 Save the code and open the page in your browser It should appear as in Figure 5 -3: Functions Figure 5 -3 How It Works This example builds on the SimpleFunction.aspx... Out Using Web Controls as Parameters 1 Create a new ASP.NET page called ParameterWebControl.aspx and save it in your Ch05 folder 2 Add the following code to this page: void Page_Load() { MakeItalic(Label1, CheckBox1.Checked); MakeItalic(Label2, CheckBox2.Checked); MakeItalic(Label3, CheckBox3.Checked); } void MakeItalic(Label TargetLabel,... view: void Page_Load() { if (IsPostBack) { lblMessage.Text = "First Line"; InsertLinebreak(Convert.ToInt32(NumberOptions.SelectedItem.Value), 165 Chapter 5 Convert.ToInt32(WidthOptions.SelectedItem.Value)); lblMessage.Text += "Second Line"; InsertLinebreak(Convert.ToInt32(NumberOptions.SelectedItem.Value), Convert.ToInt32(WidthOptions.SelectedItem.Value));... parameter array in your function definition, but that is outside the scope of this book For more information on function overloading and parameter arrays, take a look at Beginning Visual C# by Karli Watson, Wrox Press, ISBN 0-7645- 438 2-2 Web Controls as Parameters It's worth noting that when you want to pass the name of a Web control object to a function as a parameter, you need to be on your toes Let's... value="100">100 pixels wide 30 0 pixels wide 600 pixels wide 1 Line 2 Lines 3 Lines There's also a... Also notice that underneath the table is a button to notify ASP.NET that you've made your choice of labels to change: Our MakeItalic() function receives two parameters and can be found inside the tags The first parameter is a reference to an ASP.NET Label Web control; therefore it must be of the datatype... MakeItalic(Label3, CheckBox3.Checked); } A good question arises when you study this code In the form, instead of three independent CheckBox controls, why not use a asp:CheckBoxList and then have the three calls made to MakeItalic() in a loop with the counter equal to CheckBoxList.Item()? The problem is that we want to present the page in a table, and table tags like do not co-exist well with code to . runat="server"> < ;asp: ListItem value=" ;1& quot;> ;1 Line< /asp: ListItem> < ;asp: ListItem value="2">2 Lines< /asp: ListItem> < ;asp: ListItem value=" ;3& quot;> ;3 Lines< /asp: ListItem> < /asp: DropDownList> There's. Line< /asp: ListItem> < ;asp: ListItem value="2">2 Lines< /asp: ListItem> < ;asp: ListItem value=" ;3& quot;> ;3 Lines< /asp: ListItem> < /asp: DropDownList> < ;asp: Button id="Button1". runat="server"> < ;asp: ListItem value=" ;10 0"> ;10 0 pixels wide< /asp: ListItem> < ;asp: ListItem value=" ;30 0"> ;30 0 pixels wide< /asp: ListItem> < ;asp: ListItem value="600">600

Ngày đăng: 13/08/2014, 04:21

TỪ KHÓA LIÊN QUAN