There are often times that you want to do something different based on the value of a variable. Maybe you want to go to different webpages, or show different prompts on the screen. The if-then and CASE statements help you do that!
When you write code, you often want the code to do something different depending on what a user inputs, what time of day it is, and so on. There are a variety of ways that you can do these sorts of branches in your code. Each is good for a different purpose.
First, the if-then statement. This is the most common in programming, and is the easiest to understand. If something is true, then the code executes. If it’s not true, the code does not execute. You can use a ‘else’ area to execute the ‘false’ half of the equation.
For example, say you are doing something with a Member. You want to do different things if this is a new member vs an existing member. You would write:
if NewMember = TRUE then Response.Write "Welcome, new member!" else Response.Write "Welcome back, existing member!" end if
If the top IF line is true, then the code after it executes. If it is false, the ‘else’ code executes.
The if-then-else works with any kind of variable, not just a true-false one. For example, you could test:
if BooksBought> 50 then Response.Write "Wow, you must love to read books!" else Response.Write "Thank you for buying books from our site." end if
The next common sort of selection is a CASE statement. You use this if you want to test for various values in a variable without writing if-then-if-then-if-then lots of times. For example, you could do something like this:
select case FavoriteColor case "Green" Response.Write "It's not easy being green - but it's a grassy color!" case "Blue" Response.Write "Blue eyes, baby's got blue eyes ..." case "Red" Response.Write "Red Red Wine ..." case else Response.Write "Jeez, I've never heard of that color before!" end select
This page is lesson six in my free ASP Classic Course. Click below to enjoy the full course from start to finish!