Build Your Own ASP.NET 3.5 Website Using C# & VB (17 page)

Read Build Your Own ASP.NET 3.5 Website Using C# & VB Online

Authors: Cristian Darie,Zak Ruvalcaba,Wyatt Barnett

Tags: #C♯ (Computer program language), #Active server pages, #Programming Languages, #C#, #Web Page Design, #Computers, #Web site development, #internet programming, #General, #C? (Computer program language), #Internet, #Visual BASIC, #Microsoft Visual BASIC, #Application Development, #Microsoft .NET Framework

BOOK: Build Your Own ASP.NET 3.5 Website Using C# & VB
5.1Mb size Format: txt, pdf, ePub

in his electronic shopping cart. Of particular note is the C# equality operator, ==,

which is used to compare two values to see if they’re equal. Don’t use a single equals

sign in C# unless you’re assigning a value to a variable; otherwise, your code will

have a very different meaning than you expect!

Breaking Long Lines of Code

Since the message string in the above example was too long to fit on one line in this

book, we used the
string concatenation operator
to combine two shorter strings on

separate lines to form the complete message; & in VB and + in C#. In VB, we also

had to break one line of code into two using the
line continuation symbol
(_), an

underscore at the end of the line to be continued). Since C# marks the end of each

command with a semicolon (;), you can split a single command over two lines in

this language without having to do anything special.

We’ll use these techniques throughout this book to present long lines of code

within our limited page width. Feel free to recombine the lines in your own code

if you like—there are no length limits on lines of VB and C# code.

Conditional Logic

As you develop ASP.NET applications, there will be many instances in which you’ll

need to perform an action only if a certain condition is met; for instance, if the user

has checked a certain checkbox, selected a certain item from a DropDownList control,

or typed a certain string into a TextBox control. We check for such occurrences using

conditionals
—statements that execute different code branches based upon a specified

condition, the simplest of which is probably the If statement. This statement is

often used in conjunction with an Else statement, which specifies what should

happen if the condition is not met. So, for instance, we may wish to check whether

or not the name entered in a text box is Zak, redirecting the user to a welcome page

if it is, or to an error page if it’s not:

Licensed to [email protected]

68

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Visual Basic

If (userName.Text = "John") Then

Response.Redirect("JohnsPage.aspx")

Else

Response.Redirect("ErrorPage.aspx")

End If

C#

if (userName.Text == "Zak")

{

Response.Redirect("JohnsPage.aspx");

}

else

{

Response.Redirect("ErrorPage.aspx");

}

Take Care with Case Sensitivity

Instructions are case sensitive in both C# and VB, so be sure to use if in C# code,

and If in VB code. On the other hand, variable and function names are case

sensitive only in C#. As such, in C#, two variables, called x and X, would be

considered to be different; in VB, they would be considered to be the same variable.

Often, we want to check for many possibilities, and specify that our application

perform a particular action in each case. To achieve this, we use the Select Case

(VB) or switch (C#) construct, as follows:

Visual Basic

Select Case userName

Case "John"

Response.Redirect("JohnsPage.aspx")

Case "Mark"

Response.Redirect("MarksPage.aspx")

Case "Fred"

Response.Redirect("FredsPage.aspx")

Licensed to [email protected]

VB and C# Programming Basics

69

Case Else

Response.Redirect("ErrorPage.aspx")

End Select

C#

switch (userName)

{

case "John":

Response.Redirect("JohnsPage.aspx");

break;

case "Mark":

Response.Redirect("MarksPage.aspx");

break;

case "Fred":

Response.Redirect("FredsPage.aspx");

break;

default:

Response.Redirect("ErrorPage.aspx");

break;

}

Loops

As you’ve just seen, an If statement causes a code block to execute once if the value

of its test expression is true. Loops, on the other hand, cause a code block to execute

repeatedly for as long as the test expression remains true. There are two basic kinds

of loop:

■ While loops, also called Do loops (which sounds like something Betty Boop might

say!)

■ For loops, including For Next and For Each

A While loop is the simplest form of loop; it makes a block of code repeat for as

long as a particular condition is true. Here’s an example:

Licensed to [email protected]

70

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Visual Basic

LearningASP\VB\Loops.aspx

<%@ Page Language="VB" %>

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">




Loops










C#

LearningASP\CS\Loops.aspx

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




If you load this page, you’ll get the result illustrated in
Figure 3.5.

Figure 3.5. Results of a While loop

When you open the page, the label will be set to show the number 0, which will

increment to 1, then 2, all the way to 10. Of course, since all this happens in

Page_Load (that is, before any output is sent to the browser), you’ll only see the last

value assigned: 10.

These examples also demonstrate the use of two new operators: += (supported by

both VB and C#) and ++ (which is supported only by C# and is a shortcut for += 1).

The += operator adds the value on the left-hand side of the operator to the value on

the right-hand side of the operator, and then assigns the total to the variable on the

left-hand side of the operator. This operator is also available in C#, but all we want

to do here is increment a value by 1, and C# offers a more convenient operator for

that purpose: the ++ operator.

The above page demonstrates that the loop repeats until the condition is no longer

met. Try changing the code so that the counter variable is initialized to 20 instead

of 0. When you open the page now, you won’t see anything on the screen, because

the loop condition was never met.

The other form of the While loop, called a Do While loop, checks whether or not

the condition has been met at the end of the code block, rather than at the beginning.

Here’s what the above loops would look like if we changed them into Do While

loops:

Licensed to [email protected]

72

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Visual Basic

Sub Page_Load(s As Object, e As EventArgs)

Dim counter As Integer = 0

Do

messageLabel.Text = counter.ToString()

counter += 1

Loop While counter <= 10

End Sub

C#

void Page_Load()

{

int counter = 0;

do

{

messageLabel.Text = counter.ToString();

counter++;

}

while (counter <= 10);

}

If you run this code, you’ll see it provides exactly the same output we obtained

when we tested the condition before the code block. However, we can see the crucial

difference if we change the code so that the counter variable is initialized to 20. In

this case,
20
will, in fact, be displayed, because the loop code is executed once before the condition is even checked! There are some instances when this is just what we

want, so being able to place the condition at the end of the loop can be very handy.

A For loop is similar to a While loop, but we typically use it when we know in advance how many times we need it to execute. The following example displays the count of items within a DropDownList control called productList:

Visual Basic

Dim i As Integer

For i = 1 To productList.Items.Count

messageLabel.Text = i.ToString()

Next

Licensed to [email protected]

VB and C# Programming Basics

73

C#

int i;

for (i = 1; i <= productList.Items.Count; i++)

{

messageLabel.Text = i.ToString();

}

In VB, the loop syntax specifies the starting and ending values for our counter

variable within the For statement itself.

In C#, we assign a starting value (i = 1) along with a condition that will be tested

each time we move through the loop (i <= productList.Items.Count), and lastly,

we identify how the counter variable should be incremented after each loop (i++).

While this allows for some powerful variations on the theme in our C# code, it can

be confusing at first. In VB, the syntax is considerably simpler, but it can be a bit

limiting in exceptional cases.

The other type of For loop is For Each (foreach in C#), which loops through every

item within a collection. The following example loops through an array called

arrayName:

Visual Basic

For Each item In arrayName

messageLabel.Text = item

Next

C#

foreach (string item in arrayName)

{

messageLabel.Text = item;

}

The important difference between a For loop and a For Each loop involves what

happens to the variable we supply to the loop. In a For loop, the variable (we supplied i in the previous example) represents a counter—a number which starts at a Licensed to [email protected]

74

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Other books

Training His Pet by Jasmine Starr
When I Find Her by Bridges, Kate
Blood Score by Jordan Dane
Roget's Illusion by Linda Bierds
The Hen of the Baskervilles by Andrews, Donna
Criminal by Helen Chapman
Irreparable Harm by Melissa F. Miller
Love at High Tide by Christi Barth