The Select Case statement
- The Select…Case statement in VB.NET is used to select and execute one of the many groups of statements on the basis of the value of the expression in the condition. This statement is a multi-way branch statement.
- case statement enables the user to choose an option from a number of options.
- The select case statement requires only one argument/expression of any data type which is checked with the case constants. If the value of expression is matches with any case constant then that particular case statement is executed, If the value of expression does not match with any case constant then default block is executed.
- The break statement is used to exit from the current case block.
- This statement is alternate of if else ladder statements.
- In select case, default is the optional part if we don’t want to use then program will run smoothly without any error.
- The syntax of the Select…Case statement is given below:
Select [Case] (test expression)
Statement -block 2
Select statement checks the value of the expression against a list of case value and when a match is found, a block of statements associated with that Case are executed and when the match is not found then the statements associated with Case Else are executed. You can understand this concept by the following diagram:
Working with simple Select..Case statement
Here we are going to create a project in which we are using an Select..Case statement:
- Create a new project in Visual Studio 2010 by selecting File -> New Project from the menu bar. In the New Project dialog, select Windows Forms Application from the right-hand pane, enter the project name as Select..Casestatement, and click OK as shown in figure:
- Now drag and drop a Button control from the toolbox to the form and change its text property to “ShowOutput” as given below in the diagram:
- Double-click the button “ShowOutput” to open the Button1.Click event handler. Add the following given code to it:
- Now execute the project by pressing F5 key it will open a form as follows:
- Now click on the button “ShowOutput” present on the form this will show you a message box as follows:
- Now press OK button present on the message box this will show a another message box as given below:
Dim a As Integer = 3
Select Case a
MessageBox.Show("Value of a is:1")
MessageBox.Show("Value of a is:2")
MessageBox.Show("Value of a is:3")
MessageBox.Show("Value of a is:4")
MessageBox.Show("Value of a is not known")
MessageBox.Show("You are outside the Select..Case statement")