![]() |
ASP.Net Tutorial #3
Welcome to the third ASP.Net tutorial. Something I haven't mentioned is indenting of the code with tabs. By indenting blocks of code, it makes it much easier to read and to make sense of all the curly brackets which have to all be present otherwise it results in a compiler error. Right, now we get into making decisions using the if statement. It looks soemthing like this:-
<%@ Import namespace="System" %>
<html>
<head>
<title>IF</title>
</head>
<body>
<H2>IF</H2>
</body>
</html>
<script language="c#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
int i=1;
int j=2;
if(i==j)
{
Response.Write("First part of statement 1 is executed" + "<BR>");
}
else
{
Response.Write("Second part of statement 1 is executed" + "<BR>");
}
if(j>i)
{
Response.Write("First part of statement 2 is executed" + "<BR>");
}
else
{
Response.Write("Second part of statement 2 is executed" + "<BR>");
}
}
</script>
The if statements breaks down into the following set of statements:-
if something
do something
otherwise
do something else
which in C# (which we are using to code ASP.Net) terms is:-
if(something)
{
do something
}
else
{
do something else
}
So in the top of the program we assign variables as before. Then there is a block of code like this:-
if(i==j)
{
Console.WriteLine("First part of statement 1 is executed");
}
else
{
Console.WriteLine("Second part of statement 1 is executed");
}
The first section is asking if variable i is equal to (double equals signs) j then the first statement is executed and the else part is ignored. If i is not equal to j then the else comes into play and the second statement is executed and displays a different message. The if statements are always enclosed in brackets and there is no semicolon because there is an opening bracket. Purists may wonder why I always use the curly brackets when actually you can do without them. I personally always write it this way because it is clearer and gets me in to good habits.
The second block of if code has a different comparison in the brackets as follows:-
if(j>i);
This is saying if j is greater than i (the sharp right bracket) then satement 1 is executed otherwise statement 2. Other comparison operators are:-
< less than
<= less than or equal to
>= greater than or equal to
Have a play around with the code. Try these comparisons and switch them around and see if they react the way you expect. I was hoping to be able to show you haow to use messageboxes in ASP.Net but as yet I've no success. I'll update here is I ever manage it.
I think that wraps it up for this tutorial. If you have any problems or queries then please email me at the address below. On to loops and things next time. See you there...