Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / Premier Press - C# Professional Projects

.pdf
Скачиваний:
475
Добавлен:
12.02.2016
Размер:
14.7 Mб
Скачать

858

Part X

APPENDIXES

 

 

 

The following operators are supported by Visual Basic .NET:

Arithmetic operators. Used for mathematical calculations.

Comparison operators. Used for comparisons.

Assignment operators. Used for assignment operations.

Concatenation operators. Used for combining strings.

Logical/Bitwise operators. Used for logical operations.

Arrays

 

F

 

 

Variables are used to store data. At times, thereYmay be situations where you need

 

 

M

to work with multiple variables that storeLa similar type of information. For exam-

ple, the names of about 50 employees need to be stored. Declaring these 50 vari-

ables is a monotonous and time-consuming task. Therefore, an array can be

 

E

declared to make the task easy.

 

 

T

 

A collection of variables ofAthe same data type is called array. The variables that form an array have the same name and are known as array elements. An index number refers to each variable in an array, which is its position in the array. The index number helps in distinguishing one array element from another. As an example,

you can declare an array containing 50 variables of the String data type in order to store the names of 50 employees. When an array is declared, you need to create and initialize all the variables immediately. When an Integer array is declared, all the elements are initialized to 0. As compared to multiple variables, it is easier to manipulate an array and its elements. You can manipulate arrays by using the various loop statements that are provided by Visual Basic .NET.

In Visual Basic .NET, all the arrays that you create are basically derived from the Array class of the System namespace. You can also use the methods and properties of the System.Array type to manipulate these arrays. The next section will discuss how to declare these arrays.

Declaring Arrays

You need to declare an array before using the array in a program, just like a variable. While declaring an array, you need to specify the array name, the data t ype of the array, and the number of variables that the array contains. In Visual Basic

.NET, you need to declare arrays in a way similar to that in which variables are

Team-Fly®

INTRODUCTION TO VISUAL BASIC .NET Appendix B 859

declared. You can do this by using the Dim statement, the Public statement, or the Private statement. The syntax that is used to declare an array is:

Dim ArrayName (NumElements) As DataType

In the syntax mentioned, the following list contains specifications:

ArrayName. Specifies the name of the array.

NumElements. Specifies the number of elements that the array can

contain.

DataType. Specifies the data t ype of the elements. This is optional.

While declaring arrays, parentheses need to be included after the array name to differentiate an array from a variable. Consider the following code statement:

Dim intArray1(10) As Integer

An Integer array by the name intArray1, which can contain 11 elements, is declared in the code mentioned above. Why are there 11 elements and not 10 as mentioned in the code? It is because arrays are zero-based. The index number, which is between 0 and 10, adds up to 11. The code mentioned previously is part of the statement given here:

Dim IntArray () As Integer = New Integer(10) {}

Differences between Visual Basic .NET and Visual Basic 6.0 in Terms of Arrays

I will now discuss some of the basic differences between Visual Basic .NET and the earlier versions of Visual Basic in terms of arrays.By default, the starting index of an array is 0 in Visual Basic 6.0, and you can change the starting index to 1 by using the Option Base statement. In addition, the starting index for individual array declarations can be changed. The number of elements in the array is equal to the number specified during an array declaration statement plus one, if the default-starting index is set to 0. However, the starting index for every array is 0 and cannot be changed in Visual Basic .NET. The Option Base statement is not supported by Visual Basic .NET. Interoperability with arrays of other programming languages is permitted because most programming languages support zerobased arrays.

860

Part X

APPENDIXES

 

 

 

Initializing Arrays

Each element of an array is initialized as if it were a separate variable. However, if an array is not initialized, then Visual Basic .NET initializes each array element to the default value of the data type of the array.

Consider the code given here. It explains how to declare and initialize an array.

Dim booksArray1(4) As String booksArray1(0) = “Introducing VB.NET” booksArray1(1) = “Introducing ADO.NET” booksArray1(2) = “Introducing VC++.NET” booksArray1(3) = “Introducing ASP.NET” booksArray1(4) = “Introducing C#”

In the previously mentioned code, an array, booksArray1, is declared that can contain five String type elements. This arr ay stores Introducing VB.NET at index 0,

Introducing ADO.NET at index 1, Introducing VC++.NET at index 2, Introducing

ASP.NET at index 3, and Introducing C# at index 4. It may be mentioned that 0 is the starting index or the lower bound that remains fixed for all the arrays. The upper bound or the end index is 4, and it can differ from one array to another.

An array can be declared or initialized in a single line by using the new keyword provided by Visual Basic .NET. This example shows how to declare an array by using a single line of code.

Dim booksArray1() As String = {“Introducing VB.NET”, “Introducing ADO.NET”,

“Introducing VC++.NET”, “Introducing ASP.NET”, “Introducing C#”}

To retrieve the values stored in a particular index position, the index number and the name of the array needs to be specified.The following statements illustrate the point:

Dim strVar As String

strVar = booksArray1(2)

After the execution of the previously mentioned statements, the value of the String type variable, strVar, which is stored in the index position 2 in booksArray1, is retrieved.

INTRODUCTION TO VISUAL BASIC .NET Appendix B 861

Collections

A collection can be considered as a group of related objects. Generally, a collection is used to work with related objects. However, collections can be made to work with any data type.

Standard Collections Provided by Visual Basic .NET

Visual Basic .NET provides you with several collections that are used to organize and manipulate objects in an efficient way. Consider an example. All the controls in a form are stored in the Controls collection. Similarly, all the forms in a Visual Basic .NET project are stored in the Forms collection. An efficient way to keep track of the objects that an application needs to create and destroy during run time is provided by a collection.

Consider an example: In an application that you have created, you need to take inputs for five text boxes from the user and then validate the data entered by the user for all of them. One way in which the code can be written is to check for each of the text boxes separately. Another way, which is relatively easy, is to check using the Controls collection. Every form has a Controls collection that represents all the controls, such as command buttons, labels, text boxes, and so on that are present in the form. You can easily perform the input validation check by using the Controls collection.

NOTE

Controls is the base class for all the controls. It is included in the

System.Windows.Forms namespace and is provided by Visual Basic .NET.

You have learned about the collections in a brief overview. I will now discuss how you can create your own collections.

Creating Collections

In addition to the various standard collections that are present in Visual Basic

.NET, you can create your own collections. For collections, Visual Basic .NET

862

Part X

APPENDIXES

 

 

 

provides the Collection class. The syntax for creating a collection is discussed as follows:

Dim CollectionName As New Collection()

In the preceding syntax, the name of the collection that you want to create is specified by CollectionName. An instance of the Collection class is created, which is declared by the New keyword in the declaration statement

After the creation of the collection, you can manipulate the creation in the same way as you would manipulate the standard collections that are provided by Visual Basic .NET. However, there are some differences between the two. Consider the following example:

Dim collection1 as New Collection()

collection1 = Controls

The preceding code creates and initializes a Collection object, collection1, with the Controls collection. However, this statement displays an error message. Why is it so? The answer is that the Controls collection and the Collection class object are not interchangeable and are of different types with different usage. In addition, they do not have the same methods and also do not use the same kinds of index values.

Procedures

Consider a scenario where you need to perform a particular task repeatedly, for instance, calculating the average of marks obtained by students in a particular subject. In a situation such as this, you can group them in a procedure instead of writing the statements repeated ly. A set of statements grouped together to perform a specific task is called procedure. You can organize your applications by using procedures that allow you to chunk and group the program code logically.

After grouping the statements in a procedure, you can call the procedure from anywhere in the application. To call a procedure means to execute a statement that further instructs the compiler to execute the procedure. After executing the code in the procedure, the statement following the statement that called the procedure is executed.The statement that is called by a procedure is called a calling statement, and it includes the name of the procedure.The calling statement also includes the

INTRODUCTION TO VISUAL BASIC .NET Appendix B 863

data values that are needed by the procedure for performing the tasks that are specified. The data values are also referred to as arguments or parameters.

Consider the example of calculating average mentioned previously. In this case, you can create a procedure that accepts the maximum and minimum marks obtained by students as data values and calculate the average. To call this procedure, the statement to be called must provide the minimum and maximum marks obtained by students as parameters.

Now consider some of the advantages that are offered by procedures. The first advantage is the reusability of code. In other words, a procedure can be created and used when it is required and if any statement has to be changed, you simply need to make the changes in a single location.This is useful mainly in the case of large and complex applications.The applications that use procedures are easier to debug. Additionally, you can easily trace the errors in a procedure without debugging the entire application code.

Now consider the scope or accessibility of procedures in an application. Similar to classes and variables, procedures have a scope. A procedure is generally declared in a class or a module. Therefore, you can call a procedure from the same class or module in which it is created. The scope of the procedure depends on the access modifiers that you use while the procedures are declared. The access modifiers supported by Visual Basic .NET are listed in Table B-3.

Table B-3 Access Modifiers for Procedures

Access Modifier

Scope

Public

A procedure with a Public access modifier can be called from any class

 

or module in the application.

Private

A procedure with a Private access modifier can be called from the

 

same class or module in which it is declared.

Protected

A procedure with a Protected access modifier can be called from the

 

same class or module in which it is declared. In addition, it can be

 

called from the derived classes of the class in which it is declared.

Friend

A procedure with a Friend access modifier can be called from any class

 

or module that contains its declaration.

 

 

864

Part X

APPENDIXES

 

 

 

Based on the functionality of procedures, they can be classified as:

Sub procedures. A sub procedure is used to perform a specific task.

Function procedures. A function procedure is used to perform the specific tasks and returns a value to the calling statement.

Property procedures. A property procedure is used to assign or access a value from an object.

Event-handling procedures. An event-handling procedure is used to perform a specific task when a particular event occurs.

Arguments

As stated earlier, variables, constants, or expressions are accepted as arguments by procedures. As a result, each time a procedure that accepts arguments is called, arguments need to be passed to the procedure. Based on the data values that are passed as arguments, the result can differ for each call to a procedure. Arguments can be passed to procedures by either value or reference.

Functions

Visual Basic .NET provides various built-in functions that can be used in applications. Some of the built-in functions are MsgBox, InputBox, CStr, DateDiff, and StrComp. The Microsoft.VisualBasic namespace contains a declaration for these built-in functions. These functions can be classified based on the tasks performed by the various built-in functions. The functions can be classified as follows:

Functions to enhance your programs are performed by the Application enhancement functions. Examples of Application enhancement func-

tions are MsgBox and InputBox.

Functions to manipulate strings are performed by String functions. Examples of String functions are StrComp, Len, and Trim.

Functions to manipulate date and time values are performed by the Date function. Examples of Date functions are DateDiff, Now, and Month.

Functions to convert one data type to another are performed by the Conversion function. Examples of Conversion functions are CStr, CDate, and Val.

INTRODUCTION TO VISUAL BASIC .NET Appendix B 865

Having discussed the components of Visual Basic .NET, you can use this knowledge to create a simple application in Visual C# .NET.

Creating a Simple Visual C# .NET

Windows Application

In this section, you will create a simple Visual C# .NET Windows application. Then, I will discuss how to create the same application in Visual Basic .NET. Doing this will help you to appreciate how easy it is to convert an application created in one of the languages of the .NET Framework to another. In addition, you will be able to realize how closely the two languages of the .NET Framework, Visual Basic .NET and Visual C# .NET, are related.

Now, I will proceed with creating a simple Windows application in Visual C#

.NET. Name this application SampleWindowsApplication. This application accepts a username and password from the user. After specifying the required information, the user clicks on the Submit button. A message box showing the

text The user name and password that you have specified is accepted. is dis-

played. In addition, the Windows form consists of an Exit button that is used to exit the Windows application. To create SampleWindowsApplication, include two label controls, two text box controls, and two command controls to the Windows form. Next, change the following properties of the controls:

Form1

Name: frmAcceptUserInput

Text: Accept User Input

Label1

Name: lblUserName

Text: User Name

Label2

Name: lblPassword

Text: Password

866

Part X

APPENDIXES

 

 

 

Textbox1

Name: txtUserName

Textbox2

Name: txtPassword

PasswordChar: [*]

Button1

Name: btnSubmit

Text: submit

Button2

Name: btnExit

Text: Exit

After dragging the controls to the form, your SampleWindowsApplication looks as shown in Figure B-1.

FIGURE B-1 SampleWindowsApplication with the cont rols added

INTRODUCTION TO VISUAL BASIC .NET Appendix B 867

Now, to add the functionality to the application, you need to write code for the button controls. After adding code to the button controls, the code for the application is as shown:

using System.Drawing; using System.Collections;

using System.ComponentModel; using System.Windows.Forms; using System.Data;

namespace SampleWindowsApplication

{

public class frmAcceptUserInput : System.Windows.Forms.Form

{

private System.Windows.Forms.Label lblUserName; private System.Windows.Forms.Label lblPassword; private System.Windows.Forms.Button btnSubmit; private System.Windows.Forms.Button btnExit; private System.Windows.Forms.TextBox txtUserName; private System.Windows.Forms.TextBox txtPassword;

private System.ComponentModel.Container components = null;

public frmAcceptUserInput()

{

InitializeComponent();

}

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}