In the previous examples the If statement checks a condition and takes action on a True condition; it does not take any action on a False condition. An If...Else alternative form of the statement permits action on both True and False conditions. This format is shown below.
Here, the script takes alternative courses of action depending on the results of the condition test. If the expression is evaluated as True, then the immediately following set of statements is executed; if the expression is evaluated as False, the set of statements following the Else is executed. Thus, one of two different processing actions take place.
The following script is an example of the If...Else form of condition testing.
Sub Check_Button (Src As Object, Args As CommandEventArgs) If Args.CommandName = "First Button" Then Message.Text = "You clicked the first button." Else Message.Text = "You clicked the second button." End If End Sub <asp:Button Text="Click Me" runat="server" OnCommand="Check_Button" CommandName="First Button"/> <asp:Button Text="Click Me" runat="server" OnCommand="Check_Button" CommandName="Second Button"/> <asp:Label id="Message" runat="server"/>
The clicked button calls the Check_Button procedure, passing the CommandName of the button as an argument. The If statement tests this Args.CommandName. If its value is "First Button" then the first Message.Text assignment is made; otherwise (Else) the second Message.Text assignment is made.
Nesting If Statements
Two or more If statements can be nested. That is, an If statement can appear inside an If statement, which can appear inside an If statement, and so forth. In a general form these nested If statements appear as follows.
You need to be cautious, however, about nesting if statements too deeply. It is easy to get lost in the logic and the syntax. Often, you can reformulate the logic of comparisons and make simpler combinations of tests.