Branching Logic


Sams Teach Yourself ASP.NET in 21 Days, Second Edition
By Chris Payne
Table of Contents
Day 3.  Using Visual Basic.NET and C#

Branching logic causes code execution to branch in different directions. Typically, this type of logic is used when some code needs to be used over and over again from different locations.

In the factory example, every time a clock is assembled, it needs to be put in a box. The boxing machine is in the basement. When you're through with a clock, you send it to the basement for a box, and then it comes right back up for you to apply the proper postage. The boxing machine is essentially branching logic it can be used from any location in the factory, not just your assembly line. Putting a single boxing machine in the basement is much more efficient than putting one next to each assembly line.

There are two types of branching logic controls in VB.NET: functions and subroutines. The only difference between the two is that functions send information back to whatever called them, and subroutines don't. In other words, functions compute values, and subroutines perform actions. In C#, there is only a function, and it may or may not return values. These two controls are essential to ASP.NET development without them, nothing would get done. Let's examine subroutines first.


Subroutines (sometimes called procedures) in VB.NET follow this format:

 Sub name (parameters)    code End Sub 

In C#:

 void name (parameters) {    code } 

In VB.NET you use the keyword sub, but there is no corresponding keyword in C#. The word that precedes the name of the function in C# describes the data type that is returned by the function. void means no value is returned (we'll see more on this in a moment).

You've been looking at this type of syntax already in all of your ASP.NET pages. Recall this line:

 sub Page_Load(Sender as object, e as EventArgs)    code end sub 

Listing 3.10 contains some code in VB.NET that multiplies numbers; Listing 3.11 shows the same code in C#.

Listing 3.10 Multiplying Numbers in a Subroutine
 1:    <%@ Page Language="VB" %> 2: 3:    <script runat="server"> 4:       sub Page_Load(obj as object, e as eventargs) 5:          MultiplyNumbers(8,9) 6: 7:          MultiplyNumbers(4,12) 8: 9:          MultiplyNumbers(348,23) 10:       end sub 11: 12:       sub MultiplyNumbers(intA as integer, intB as integer) 13:          Response.Write(intA * intB & "<br>") 14:       end sub 15:    </script> 16: 17:    <html><body> 18: 19:    </body></html> 
Listing 3.11 Multiplying Numbers in a Subroutine in C#
 1:    <%@ Page Language="C#" %> 2: 3:    <script runat="server"> 4:       void Page_Load(Object Sender, EventArgs e) { 5:          MultiplyNumbers(8,9); 6: 7:          MultiplyNumbers(4,12); 8: 9:          MultiplyNumbers(348,23); 10:       } 11: 12:       void MultiplyNumbers(int intA, int intB) { 13:          Response.Write(intA * intB + "<br>"); 14:       } 15:    </script> 16: 17:    <html><body> 18: 19:    </body></html>*** 


In the code declaration block on line 12, you create a subroutine named MultiplyNumbers. The variables in the parentheses are called parameters or arguments. These are values that are passed into the subroutine from the code that's using it. The subroutine can use these values to perform any actions it needs to. A group of parameters is called a parameter list. Specifying these parameters is very similar to declaring variables (note the differences between C# and VB.NET). The parameters you declare here must be passed in by the calling code that uses this subroutine, or else you'll receive errors.

On line 13, you write the product of these parameters to the browser using Response.Write, and you close the subroutine on line 14. Now that you've created the subroutine, you can use it from anywhere else on the page. This subroutine will never execute unless you tell it to explicitly it won't execute just because you put it there.


On line 5 you call the subroutine. This tells the program to execute the code inside the subroutine and come back to line 5 when it's done (you can see the branching logic at work here). When you call MultiplyNumbers, you specify the two parameters that the subroutine defined two Integers. MultiplyNumbers takes these integers and performs its actions.

Lines 7 and 9 do identical things but pass different parameters to the subroutine. This is part of the beauty of branching logic controls you can call them from anywhere and give them different parameters to play with each time. This code will produce what's shown in Figure 3.7.

Figure 3.7. Using subroutines to perform encapsulated logic.



If you're familiar with VBScript and traditional ASP, you may remember calling subroutines and functions with the following syntax:

 MultiplyNumbers 8, 9 

That is, without parentheses. With C#, VB.NET, and ASP.NET, you must always include the parentheses when calling a function or there will be an error.


Functions are very similar to subroutines their syntax is nearly identical, and they can both perform the same actions. Functions, however, return a value to the code that called it. Let's modify Listing 3.10 to use a function instead of a subroutine.

Listing 3.12 Multiplying Numbers in a Function
 1:    <%@ Page Language="VB" %> 2: 3:    <script runat="server"> 4:       sub Page_Load(obj as object, e as eventargs) 5:          Response.Write(MultiplyNumbers(8,9) & "<br>") 6: 7:          Response.Write(MultiplyNumbers(4,12) & "<br>") 8: 9:          Response.Write(MultiplyNumbers(348,23) & "<br>") 10:       end sub 11: 12:       function MultiplyNumbers(intA as integer, intB as integer) _ 13:          as Integer 14:          Return intA * intB 15:       end function 16:    </script> 17: 18:    <html><body> 19: 20:    </body></html> 


The MultiplyNumbers function would look like the following code snippet in C#:

 12:       int MultiplyNumbers(int intA, int intB) { 13:          return(intA * intB); 14:       } 

This code is slightly different from Listing 3.10. The first difference is that the function on line 12 doesn't write the product of the two parameters to the browser. Rather, it uses the return keyword to send the product back to the code that called it. Note that the function also specifies As Integer after the parameter list (or int in front of the function name in C#). This is used to tell the calling code what type of data to expect in return. This listing produces the same output as the previous listing. On line 5, you call MultiplyNumbers inside a Response.Write. This seems kind of odd at first glance, but let's examine it further. First, line 5 calls MultiplyNumbers with the parameters 8 and 9. Then this function takes over, multiplies the two parameters on line 14, and returns them to line 5. Response.Write on line 5 now only sees the product, 72. It's equivalent to writing Response.Write(72).

This allows you to use function calls in many different places. For example, you could write any of the following:

 MultiplyNumbers(8,9) intCount = MultiplyNumbers(8,9) * 72 if MultiplyNumbers(8,9) < 80 then    ... 

These all work because the function executes first and the code will end up seeing only the returned value. There are two ways to return values in VB.NET. The first way you've already seen using the keyword return. The second way is to assign the return value to the function itself. For example, the following works the same way as the function in Listing 3.12:

 12:    function MultiplyNumbers(intA as integer, intB as integer) _ 13:       as integer 14:       MultiplyNumbers = intA * intB 15:    end function 

A function doesn't have to return a value, but it may if necessary. You could have included the Response.Write statement in the function, as you did for the subroutine in Listing 3.10, but this method works for the sake of demonstration,. Optionally, you can also specify the data type of the return value:

 function MultiplyNumbers(intA as integer, intB as integer)_    as integer 

This tells the calling code that you're returning an integer.


Always make sure to specify a return type when declaring a function. This includes readability of the code and also increases type safety.

There is an important thing to note with the return keyword. Once you call return, all execution in that particular method stops, and execution returns to the calling method. In other words, if you wrote Response.Write("HI") after line 14 in Listing 3.12, it would never be executed because return passed the control back to the Page_Load method.

Optional Parameters

What happens if you think you may use a parameter for your function or subroutine, but you don't need the code to tell you what it is? You want the parameter to be optional. Luckily, VB.NET allows you to do this with the Optional keyword. Let's look at an example:

 function MultiplyNumbers(intA as integer, optional intB as__    integer = 3) as Integer    return intA * intB end function 

On the first line, you use the optional keyword to tell VB.NET that any code that calls this function isn't required to specify a value for intB, but that it may. You could then call this function with either of the following:

 MultiplyNumbers(8) MultiplyNumbers(8,9) 

What happens if the code doesn't specify a value? On the third line, you multiply the two values together. If intB wasn't specified, this would produce an error.

When you specify that a parameter is optional, you must also specify a default value. On the first line, you have optional intB as integer = 3. This tells VB.NET what this value should be in case it isn't specified.

There is one caveat to using optional: Once you specify that one parameter is optional, all subsequent parameters must also be optional. The following code would produce an error:

 function MultiplyNumber(intA as integer, optional intB as _    integer = 3, intC as integer) as Integer 

Instead, use this:

 function MultiplyNumber(intA as integer, optional intB as _    integer = 3, optional intC as integer = 4) as Integer 

In C#, there is no equivalent optional keyword. The only way to provide optional parameters is to use method overloading a concept of object-oriented programming that is out of the scope of this lesson. See the .NET Framework documentation for more details.

Event Handlers

Events, as discussed on Days 1, "Getting Started with ASP.NET," and 2, "Building ASP.NET Pages," are actions that may occur in your application a mouse click or a button press, for instance. Usually, whenever an event occurs, you need to do some processing. For example, when a Submit button is clicked, you should enter form information into a database. Or if the user clicks a link, you want to send him to the appropriate page. This functionality doesn't happen by itself you must tell the program what to do.


You do this by creating an event handler. The syntax is identical to that for a subroutine, so you should be familiar with it already. The difference lies in the parameter list. When an event is raised meaning the event has occurred it produces variables that describe the event. Your event handler can use these variables to figure out what to do.

Nearly all of the events in ASP.NET produce the same parameter list. Listing 3.13 shows an example.

Listing 3.13 Handling Events in ASP.NET
 1:    <%@ Page Language="VB" %> 2: 3:    <script runat="server"> 4:       Sub Button_Click(Sender As Object, e As EventArgs) 5:          Response.Write("You clicked the button!") 6:       End Sub 7:    </script> 8: 9:    <html><body> 10:       <form runat="server"> 11:          <asp:button  Text="Submit" 12:             runat=server 13:             OnClick="Button_Click"/><p> 14:       </form> 15:    </body></html> 


Line 4 contains what appears to be a normal subroutine. However, the parameter list distinguishes it as an event handler. The first parameter is an Object data type that represents the object that raised the event. The second parameter is a new type you haven't seen yet, EventArgs. This parameter contains any information specific to the event that occurred. Typically, this variable will be empty. This is the standard event handler parameter list, although in a few days you'll see some exceptions to the rule. In C#, this standard list looks like the following code snippet:

 void event_handler_name(Object Sender, EventArgs e) 


Remember that you can call your parameters whatever you like. You're using Sender and e here for simplicity and standardization.

On line 11, you create an ASP.NET button control. You may recall this control from Days 1 and 2, and it's explored further on Day 5, "Beginning Web Forms." For now, you just need to know that you set its ID its unique name to btSubmit, set the text it will display to Submit, and specify that it runs at the server. Whenever this button is clicked, it raises an event called Click. On line 13, you tell the button the following: "When the Click event occurs, execute the subroutine Button_Click." You just defined its event handler.

Now, whenever the button is clicked, it executes the subroutine on lines 4 6 and writes "You clicked the button!" to the browser. Save this code in a file called listing0310.aspx and view it from your browser. When you click the button, you'll see Figure 3.8.

Figure 3.8. Handling events in ASP.NET.


This is the basis for handling all actions in ASP.NET pages. Once you learn how to handle events, ASP.NET becomes much more powerful. Let's modify Listing 3.13 a bit to use the parameters supplied to the event handler as shown in Listing 3.14.

Listing 3.14 Using Event Parameters in ASP.NET
 1:    <%@ Page Language="VB" %> 2: 3:    <script runat="server"> 4:       Sub Button_Click(Sender As Object, e As EventArgs) 5:          Response.Write(Sender.Text) 6:       End Sub 7:    </script> 8: 9:    <html><body> 10:       <form runat="server"> 11:          <asp:button  Text="Submit" 12:             runat=server 13:             OnClick="Button_Click"/><p> 14:       </form> 15:    </body></html> 


When you view this page and click the button, you'll see the word "Submit" in place of "You clicked the button!" Let's examine line 5. Recall that the first parameter represents the object that raised the event. In this case, it happens to be the Submit button. Thus, obj is one name you can use to reference this button. The other name is the id value, btSubmit. Line 5 writes the Text property of the button to the browser. On line 11, the Text property is set to "Submit". You could change line 5 to read as follows and it would produce the same output:


But we're getting ahead of ourselves. You'll examine this more thoroughly on Day 5.


Generally, events in ASP.NET can be handled only if the code that generates them lies within <form></form> tags. This is because the events must be posted to the server, which will be discussed in more detail on Day 5.

There's another event that you've been using quite a bit in today's examples: the Page_Load event. Recall Listing 3.12, for example. On line 4 is a method called Page_Load, with the standard event parameter list: Sender as object, e as EventArgs. When an ASP.NET page loads, the Page_Load event is raised and you can use it to do some processing. Typically, you'll use this event handler to display something to the user as soon as the page loads. Day 4, "Using ASP.NET Objects with C# and VB.NET," will take a closer look at this event.


    Sams Teach Yourself ASP. NET in 21 Days
    Sams Teach Yourself ASP.NET in 21 Days (2nd Edition)
    ISBN: 0672324458
    EAN: 2147483647
    Year: 2003
    Pages: 307
    Authors: Chris Payne

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: