PASSING OPTIONAL ARGUMENTS


Visual Basic also provides you with the ability to set up procedures that can process optional arguments. There are a few rules that you need to be aware of when setting up a procedure to accept optional arguments. First of all, you must remember to define a default value for any Optional argument. The default value must be expressed as a constant value. In other words, you cannot use a variable or other type of value. Finally, any argument that follows an Optional argument must also be an Optional argument.

The following example demonstrates how to set up a procedure with an Optional argument.

 Sub DisplayMessage(Optional ByVal strUserName As String = "")          MessageBox.Show("Greetings " & strUserName) End Sub 

You can call the Sub procedure in the previous example without passing it an argument, as shown below.

 DisplayMessage() 

Alternatively, you can call the Sub procedure and pass it an argument, as demonstrated here.

 DisplayMessage("Alexander Ford") 

As mentioned above, you can set up your procedures to process more than one Optional argument at a time, as demonstrated below.

 Public Sub DisplayMessage(ByVal strMessage As String, _       Optional ByVal strTitleBarMessage As String = "", _       Optional ByVal strIcon As String = "")         If strIcon = "Exclamation" Then             MessageBox.Show(strMessage, strTitleBarMessage, _               MessageBoxButtons.OK, MessageBoxIcon.Exclamation)         Else             MessageBox.Show(strMessage, strTitleBarMessage, _               MessageBoxButtons.OK, MessageBoxIcon.Information)         End If End Sub 

You can call the previous Sub procedure in a number of different ways. For example, the following statement calls the procedure and passes it three arguments.

 DisplayMessage("The current date and time are " & Now(), "Demo", _   "Exclamation") 

You can also call the procedure and pass it just two arguments, as shown below.

 DisplayMessage("The current date and time are " & Now(), "Demo") 

You can also call the procedure as shown below.

 DisplayMessage("The current date and time are " & Now(), , _   "Information") 

In the last example, arguments representing the procedure's first and third parameters were passed. Notice that to make this work, I had to include a comma where the procedure's second parameter is defined.

Figure 8.9 shows how the pop-up windows produced by the three previous calling statements will look when displayed.

image from book
Figure 8.9: Using the Optional keyword, you can create flexible procedures that can process different numbers of arguments.




Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
ISBN: 1592008143
EAN: 2147483647
Year: 2006
Pages: 126

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net