Introducing Variables


Variables are basically values that can change, in other words, they can be assigned different values, hence their name. In ASP.NET pages, variables can only exist in memory from the time when the server receives a request for the page, until the time when the server has finished sending the page back to the web browser. This is not very long at all – often less than a second. You might think this means variables are not very useful. You'd be wrong. Even in this short time, variables can be extremely useful.

You'll be pleased to know that we've already met several different types of variables. In the previous chapter, we looked at looping structures that did some simple counting using variables that were Integers. We also used the String data type when passing in arguments to the e-mail function, which means that we used strings to communicate with the function. Strings and integers are two examples of simple data types.

Declaring Variables

If you want to store some information in real life, you need something to write it on – such as a piece of notepaper, your hand, a wall, or whatever. Similarly, information in Visual Basic .NET is stored in variables, and before you can store any information you need a variable in which to store it.

Visual Basic .NET already knows how to make variables – you just need to ask for one. This is called declaring a variable because you are stating that a piece of memory is going to be used for a particular purpose. When you declare a variable, you also need to declare what type of data the variable will store. This is called the variable's data type. If you don't ask for the right sort of variable, you'll end up not being able to store the information you want.

The easiest way to declare a variable is using the Dim keyword, like this:

 Dim emailAddress As String 

The Dim keyword means, "I want a new variable", and is short for dimension. When you create a variable you can give it any name you want – but you should always try to use a name that describes what the variable is for. This makes it easier to understand your programs. I've called mine emailAddress, which is pretty clear. (I've written enough programs with variables called eA to know full names are a good idea.)

Next, we say what data type we want; in this case, we want a String. In programming, a string means a sequence of characters – effectively a piece of text, but doesn't have to contain just letters. Our emailAddress variable is used to hold text. Data types are very important because they define what sort of data variables can store, how they behave, and what they can do. We will look at several data types in this chapter, as well as the various operations that can be performed on the different types. In the following two Try It Outs, you'll see how – even if a data type can store the information you need, if it's the wrong choice then the variable can behave strangely.

Try It Out—Using Variables

In this example, we're going to create an ASP.NET page that can do some simple math. You'll soon see that – if you want simple math to stay simple – you need to choose the right data type to start with.

  1. Start up Web Matrix, and create a new ASP.NET page called Variables.aspx.

  2. Drag a Label control onto the page, then type + with a space on either side, drag on another Label, then type =, again with a space on either side, and finally add another Label. Next add a new line by pressing the Enter key, and drag a Button control onto the page. Your page should end up looking like this:

    click to expand

  3. We won't bother with setting up properties this time – just double-click the button to wire up the event handler, and add the following code:

    Sub Button1_Click(sender As Object, e As EventArgs)  Dim myFirstNumber, mySecondNumber As Integer  myFirstNumber = 7  mySecondNumber = 8  Label1.Text = myFirstNumber  Label2.Text = mySecondNumber  Label3.Text = myFirstNumber + mySecondNumber End Sub
  4. Now run the page using F5 or the Start button and when it appears, click the button. You should see the following:

    click to expand

How It Works

We'll be coming back to this example in a minute, but let's just have a look at what happened when we clicked the button.

First of all, we created two new variables for representing whole numbers, in other words of type Integer:

  Dim myFirstNumber, mySecondNumber As Integer

In Visual Basic .NET, you can declare lots of variables of the same type in one line – you just separate the names by a comma. So, we have two variables for holding numbers, myFirstNumber and mySecondNumber. Next, we put some numbers into the variables:

  myFirstNumber = 7   mySecondNumber = 8

myFirstNumber now has a value of 7, and mySecondNumber now has a value of 8. These numbers are stored in memory, and we can retrieve the values by the names we selected for our variables. The next two lines set our first two Label controls to display these values:

  Label1.Text = myFirstNumber   Label2.Text = mySecondNumber

So, we've already got the "7 + 8 =" bit, next we need to actually do the math. Adding the two variables together is really easy – we just set Label3.Text to myFirstNumber plus mySecondNumber and this gives us a result of 15:

  Label3.Text = myFirstNumber + mySecondNumber 

This worked pretty well, but if we'd used the wrong data type, things would have behaved very differently, as we'll see!

Try It Out—Your First Bug
  1. Go back to your code, and change the declaration so that we create two String variables instead of two Integer variables:

      Dim myFirstNumber, mySecondNumber As String 
  2. Now run the page again, and click the button again. The result is quite different:

    click to expand

How It Works

We have now ended up with 7 + 8 = 78 for some reason. While this isn't mathematically correct, it's not too hard to work out what's gone wrong. Instead of adding the numbers together, our program has concatenated the two numbers, writing a 7, and then an 8 to the page. In other words, the two numbers have been simply stuck together to give the final result of 78!

This is exactly the sort of the problem that can occur if you don't use the correct data type. Strings are designed for storing text, so you can't really do math with them – if you "add" two strings, Visual Basic .NET will simply join them together.

Important

If you don't declare variables with the correct data types, your program may produce unexpected and unwanted results at best, if not errors. Make sure you declare variables with the correct data types!

Where Can I Use My Variables?

As we saw in the last chapter, the Code view in Web Matrix can contain functions and procedures: self-contained blocks of code. There is also the area of the code window that is outside any particular function or procedure. Variables can be declared inside any function or procedure, or in the area outside a function or procedure. However, the place where you declare variables affects the places where you can access them, and how long they retain their values.

In the last example we declared our variables inside the Button1_Click procedure, but that's not the only place we could do it. Let's say that we want to have two buttons on our form – one to add the numbers together, and one to subtract one from the other. Before we do that though, fix the bug by changing the Dim statement back to As Integer:

  Dim myFirstNumber, mySecondNumber As Integer 

Now that's fixed, the button does this, as we saw earlier:

  1. Declares two Integer variables

  2. Sets each variable to a number – one is set to seven, and the other to eight

  3. Sets Label1.Text to myFirstNumber, and Label2.Text to mySecondNumber

  4. Sets Label3.Text to myFirstNumber added to mySecondNumber

Next, go back to Design view, and change the existing button's Text property to Add, then drag a new one next to it and set its Text property to Subtract. The second button will do exactly the same as the Add button for the first of three steps listed above – only the fourth step is different because we want to subtract instead of add.

We could just retype most of our addition code into the subtract button's event handler. That way, we'd have two lots of code that do the same thing, which is a waste – and will become even more of a waste if we decide to add more buttons. So let's make a procedure to carry out the first three steps, and then we can call it from both of the buttons.

Go back to Code view, and add the following procedure:

 Sub SetVarsToInitialValues() End Sub 

Now select everything from Button1_Click, except for the last line – the line where we do the addition. Either cut-and-paste or drag this code into the SetVarsToInitialValues() procedure. Now add a call to SetVarsToInitialValues() at the start of Button1_Click, so that your code should look like the following:

Sub SetVarsToInitialValues()   Dim myFirstNumber, mySecondNumber As Integer   myFirstNumber = 7   mySecondNumber = 8   Label1.Text = myFirstNumber   Label2.Text = mySecondNumber End Sub Sub Button1_Click(sender As Object, e As EventArgs)  SetVarsToInitialValues()   Label3.Text = myFirstNumber + mySecondNumber End Sub

Now try running the page. It won't work. You'll get a compilation error, which means that ASP.NET cannot work out what your code means. The problem line is:

  Label3.Text = myFirstNumber + mySecondNumber

and the complaint is that we didn't declare myFirstNumber. Hold on, we did declare it, in the SetVarsToInitialValues() procedure! What is going on?

Our myFirstNumber is now declared inside the SetVarsToInitialValues() procedure, but we try to use it in the Button1_Click procedure. This won't work because if you declare a variable inside a procedure or function, it ceases to exist as soon as the procedure or function finishes. In fact, if you declare a variable inside a function (or procedure), you can only see it from inside that function. Variables declared within a procedure or function are limited to that procedure or function, unless you pass them into another procedure or function as an argument – as we saw in the previous chapter.

Fortunately, there's a really easy way to fix this particular problem – just move your declaration outside any procedures. If you do that, you can use the variables from anywhere in the page, so move the declaration from inside SetVarsToInitialValues() to the area outside any function or procedure:

 Dim myFirstNumber, mySecondNumber As Integer Sub SetVarsToInitialValues()   myFirstNumber = 7   mySecondNumber = 8   Label1.Text = myFirstNumber   Label2.Text = mySecondNumber End Sub Sub Button1_Click(sender As Object, e As EventArgs)   Label3.Text = myFirstNumber + mySecondNumber End Sub 

The variables now exist from when the page gets requested right through to when it gets displayed, and any function or procedure in the page can use them.

Important

The places where a variable is accessible are known as the variable's 'scope'.

Let's clarify this a bit more. Take a look at the following table, which compares the behavior of variables declared inside a procedure or function with those declared outside:

Variable declared

Is alive

Can be used by

Inside a function or procedure

For as long as that function or procedure runs

The function or procedure where the variable is declared. Functions and procedures you call from within this one can receive the variable as an argument.

Outside any functions or procedures

From the time the page is requested, until all of the code has run

Any code in the page.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net