Visual Basic 2008 Programming: Business Applications with a Design Perspective
Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9
Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Appendix A Appendix B Appendix C Home
Loading
Last change: February 13 2016 18:48:19.

 Chapter in PDF

Table of Contents

Chapter 5: Decision
Last change: February 13 2016 18:47:58.
<<PreviousNext>>

Simple If Block

When a condition is true, you may need to execute more than one statement. In such cases, the previous simple structure would be deficient. The following simple If block will serve the purpose better:

If Condition Then Statements to be executed End If

Notice that the first line of the block starts with an If, and ends with the keyword Then. There should be no other expression or statement (except for comments) after Then; otherwise, the line will be interpreted as a simple If statement explained previously. Also notice that the block ends with an End If statement. All statements within these two lines will be executed when the condition in the If line is True. Consider the following code in an event procedure:

Private Sub chkSort_CheckedChanged(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles chkSort.CheckedChanged If chkSort.Checked Then cboSortField1.Enabled = True cboSortField2.Enabled = True End If End Sub

The If statement checks to see whether the chkSort check box is checked. If so, both the combo boxes containing sort field 1 and sort field 2 are enabled. (Note: To test the preceding code, set the Enabled property of the two combo boxes to False at design time.)
What happens to the two combo boxes in the previous example if the check box is clicked off? Nothing inside the If block will be executed. Both can be either enabled or disabled before the event procedure is triggered; however, once enabled, no code inside the procedure will disable the two combo boxes.
What if you really mean to disable the two combo boxes when the check box is clicked off? Given what you have learned in this chapter so far, one way to solve this is to code the procedure as follows:

Private Sub chkSort_CheckedChanged(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles chkSort.CheckedCahnged cboSortField1.Enabled = False cboSortField2.Enabled = False If chkSort.Checked Then cboSortField1.Enabled = True cboSortField2.Enabled = True End If End Sub

In the code, the two combo boxes will always be disabled first (regardless of the check state of the check box) and then enabled if the check box is found checked.

Last change: February 13 2016 18:47:58.
<<PreviousNext>>